From daa7613ec089a35153e3b110335ecb02f8943bf9 Mon Sep 17 00:00:00 2001 From: Dizzy Rogers <19627670+Diizzayy@users.noreply.github.com> Date: Thu, 7 Apr 2022 16:13:19 +0000 Subject: [PATCH 01/10] docs: api routes --- .../2.guide/2.features/9.api-routes.md | 107 +++++++++++++++++- 1 file changed, 103 insertions(+), 4 deletions(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index ec902b2df74..28a087ee70a 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -1,7 +1,106 @@ # API Routes -::NeedContribution -:: +Nuxt will automatically register files in the `/server/api` directory to create API endpoints. -::ReadMore{link="/guide/directory-structure/server"} -:: +To handle requests, each file can export as a default function or an instance of a [h3 app](https://github.com/unjs/h3#usage) to add even more functionality to an API route. These can directly return a promise, JSON data or simply use `res.end()`. + +Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions). + +## Route Parameter + +For ease of use, routes that are dependent on a parameter can specify the parameter within brackets in the file name `/api/hello/[parameter].ts`. + +```ts [/server/api/hello/[name].ts] +export default eventHandler(event => { + return `Hello, ${event.context.params.name}!` +}) +``` + +## Method Matching + +Routes can be suffixed with `.get`, `.post`, `.put`, `.delete` to match a [supported HTTP Method](https://github.com/unjs/nitro/blob/main/src/runtime/virtual/server-handlers.d.ts#L7). + +```ts [/server/api/test.post.ts] +export default eventHandler(() => 'Test post handler') +``` + +Given the example above, the `test` route will be declared as a `POST` route. + +## Catch All Route + +A catch all route can be defined by creating a file in the `api` directory with the name `[...].ts`. This route will be triggered for all requests that do not match any other route. + +This is useful for special usecases as well as fallback error handling. + +```ts [/server/api/[...].ts] +export default eventHandler(event => `Default page`) +``` + +## Examples + +### Hello World + +```ts [/server/api/hello.ts] +export default eventHandler(() => '

Hello World

') +``` + +### POST Request + + + + +```ts [/server/api/hello.ts] +export default eventHandler(async (event) => { + const body = await useBody(event.req); // only for POST | PUT | PATCH | DELETE requests + + return { body } +}) +``` + + + + +```ts [/server/api/hello.post.ts] +export default defineEventHandler(() => '

Hello World

') +``` + +
+
+ +### Using Router + +```ts [/server/api/hello.ts] +import { createApp, createRouter } from 'h3' + +const app = createApp() +const router = createRouter() + +app.use(router) + +router.get('/', () => 'Hello World') + +export default app +``` + +### Using Node.js style + +```ts [server/api/node.ts] +import type { IncomingMessage, ServerResponse } from 'http' + +export default async (req: IncomingMessage, res: ServerResponse) => { + res.statusCode = 200 + res.end('Works!') +} +``` + +### Access Request Data + +```ts +export default eventHandler(async (event) => { + const params = event.context.params; + const body = await useBody(event.req); // only for POST | PUT | PATCH | DELETE requests + const cookies = useCookies(event.req); + + return { params, body, cookies }; +}); +``` \ No newline at end of file From cc55710d4b4f336012df4c6276b371a5bd357a2e Mon Sep 17 00:00:00 2001 From: Dizzy Rogers <19627670+Diizzayy@users.noreply.github.com> Date: Thu, 7 Apr 2022 16:20:38 +0000 Subject: [PATCH 02/10] docs: fix typos --- docs/content/2.guide/2.features/9.api-routes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index 28a087ee70a..22bd408a9eb 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -2,7 +2,7 @@ Nuxt will automatically register files in the `/server/api` directory to create API endpoints. -To handle requests, each file can export as a default function or an instance of a [h3 app](https://github.com/unjs/h3#usage) to add even more functionality to an API route. These can directly return a promise, JSON data or simply use `res.end()`. +To handle requests, each file can export a default function or an instance of a [h3 app](https://github.com/unjs/h3#usage) to add even more functionality to an API route. These can directly return a promise, JSON data or simply use `res.end()`. Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions). @@ -30,7 +30,7 @@ Given the example above, the `test` route will be declared as a `POST` route. A catch all route can be defined by creating a file in the `api` directory with the name `[...].ts`. This route will be triggered for all requests that do not match any other route. -This is useful for special usecases as well as fallback error handling. +This is useful for special use cases as well as fallback error handling. ```ts [/server/api/[...].ts] export default eventHandler(event => `Default page`) From f9ded09f817a9da011d73fd7969e29b969958c88 Mon Sep 17 00:00:00 2001 From: Dizzy Rogers <19627670+Diizzayy@users.noreply.github.com> Date: Thu, 7 Apr 2022 13:21:42 -0400 Subject: [PATCH 03/10] docs: catch-all route Co-authored-by: pooya parsa --- docs/content/2.guide/2.features/9.api-routes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index 22bd408a9eb..fd71a1647ea 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -26,7 +26,7 @@ export default eventHandler(() => 'Test post handler') Given the example above, the `test` route will be declared as a `POST` route. -## Catch All Route +## Catch-all route A catch all route can be defined by creating a file in the `api` directory with the name `[...].ts`. This route will be triggered for all requests that do not match any other route. From b07ba2564780b89af455348877e95f53cd6be682 Mon Sep 17 00:00:00 2001 From: Dizzy Rogers <19627670+Diizzayy@users.noreply.github.com> Date: Thu, 7 Apr 2022 13:46:38 -0400 Subject: [PATCH 04/10] Update docs/content/2.guide/2.features/9.api-routes.md Co-authored-by: pooya parsa --- docs/content/2.guide/2.features/9.api-routes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index fd71a1647ea..404fdda32dc 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -2,7 +2,7 @@ Nuxt will automatically register files in the `/server/api` directory to create API endpoints. -To handle requests, each file can export a default function or an instance of a [h3 app](https://github.com/unjs/h3#usage) to add even more functionality to an API route. These can directly return a promise, JSON data or simply use `res.end()`. +To handle requests, each file should export a default function (an [unjs/h3](https://github.com/unjs/h3) event handler or classic `(req, res) => {})`. The handler can directly return a JSON data, or Promise or use `event.res.end()` to send response by itself. Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions). From 1d107df9660433d3e248c3bbf8bdf4f53d2108cd Mon Sep 17 00:00:00 2001 From: Dizzy Rogers <19627670+Diizzayy@users.noreply.github.com> Date: Thu, 7 Apr 2022 18:23:56 +0000 Subject: [PATCH 05/10] docs(api-routes): improve --- .../2.guide/2.features/9.api-routes.md | 46 ++++++++++--------- 1 file changed, 24 insertions(+), 22 deletions(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index 404fdda32dc..8d4d3626f44 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -2,7 +2,7 @@ Nuxt will automatically register files in the `/server/api` directory to create API endpoints. -To handle requests, each file should export a default function (an [unjs/h3](https://github.com/unjs/h3) event handler or classic `(req, res) => {})`. The handler can directly return a JSON data, or Promise or use `event.res.end()` to send response by itself. +To handle requests, each file should export a default function (an [unjs/h3](https://github.com/unjs/h3) event handler or classic `(req, res) => {})`. The handler can directly return JSON data, a Promise or use `event.res.end()` to send response by itself. Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions). @@ -11,7 +11,7 @@ Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-fun For ease of use, routes that are dependent on a parameter can specify the parameter within brackets in the file name `/api/hello/[parameter].ts`. ```ts [/server/api/hello/[name].ts] -export default eventHandler(event => { +export default defineEventHandler(event => { return `Hello, ${event.context.params.name}!` }) ``` @@ -21,7 +21,7 @@ export default eventHandler(event => { Routes can be suffixed with `.get`, `.post`, `.put`, `.delete` to match a [supported HTTP Method](https://github.com/unjs/nitro/blob/main/src/runtime/virtual/server-handlers.d.ts#L7). ```ts [/server/api/test.post.ts] -export default eventHandler(() => 'Test post handler') +export default defineEventHandler(() => 'Test post handler') ``` Given the example above, the `test` route will be declared as a `POST` route. @@ -33,7 +33,7 @@ A catch all route can be defined by creating a file in the `api` directory with This is useful for special use cases as well as fallback error handling. ```ts [/server/api/[...].ts] -export default eventHandler(event => `Default page`) +export default defineEventHandler(event => `Default page`) ``` ## Examples @@ -41,7 +41,7 @@ export default eventHandler(event => `Default page`) ### Hello World ```ts [/server/api/hello.ts] -export default eventHandler(() => '

Hello World

') +export default defineEventHandler(() => '

Hello World

') ``` ### POST Request @@ -50,8 +50,8 @@ export default eventHandler(() => '

Hello World

') ```ts [/server/api/hello.ts] -export default eventHandler(async (event) => { - const body = await useBody(event.req); // only for POST | PUT | PATCH | DELETE requests +export default defineEventHandler(async (event) => { + const body = await useBody(event) // only for POST | PUT | PATCH | DELETE requests return { body } }) @@ -82,25 +82,27 @@ router.get('/', () => 'Hello World') export default app ``` -### Using Node.js style - -```ts [server/api/node.ts] -import type { IncomingMessage, ServerResponse } from 'http' - -export default async (req: IncomingMessage, res: ServerResponse) => { - res.statusCode = 200 - res.end('Works!') -} -``` - ### Access Request Data ```ts -export default eventHandler(async (event) => { +export default defineEventHandler(async (event) => { const params = event.context.params; - const body = await useBody(event.req); // only for POST | PUT | PATCH | DELETE requests - const cookies = useCookies(event.req); + const body = await useBody(event) // only for POST | PUT | PATCH | DELETE requests + const cookies = useCookies(event) return { params, body, cookies }; }); -``` \ No newline at end of file +``` + +### Server Routes + +It's now possible to register server handlers without the `/api` prefix, by creating a `server/routes` directory. All handlers in the `routes` directory will be registered as server routes and can be directly requested without the `/api` prefix. + +```ts [/server/routes/hello.ts] +export default defineEventHandler(() => 'Hello World!') +``` + +Given the example above, the `/hello` route will be accessible at . + +::ReadMore{link="https://github.com/unjs/nitro#routes-and-api-routes" title="Nitro Routes"} +:: \ No newline at end of file From 90c87f71c85d595924b5f1c1b3bd3e5358b5d8c5 Mon Sep 17 00:00:00 2001 From: Dizzy Rogers <19627670+Diizzayy@users.noreply.github.com> Date: Thu, 7 Apr 2022 20:09:51 +0000 Subject: [PATCH 06/10] docs: lint --- docs/content/2.guide/2.features/9.api-routes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index 8d4d3626f44..274d4d57b3b 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -105,4 +105,4 @@ export default defineEventHandler(() => 'Hello World!') Given the example above, the `/hello` route will be accessible at . ::ReadMore{link="https://github.com/unjs/nitro#routes-and-api-routes" title="Nitro Routes"} -:: \ No newline at end of file +:: From 23ff4d6544b20de98422094d1b68e4ebc4604f01 Mon Sep 17 00:00:00 2001 From: Dizzy Rogers <19627670+Diizzayy@users.noreply.github.com> Date: Thu, 7 Apr 2022 20:16:54 +0000 Subject: [PATCH 07/10] docs: lint --- docs/content/2.guide/2.features/9.api-routes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index 274d4d57b3b..ff1b5ee618f 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -67,7 +67,7 @@ export default defineEventHandler(() => '

Hello World

')
-### Using Router +### Using Router ```ts [/server/api/hello.ts] import { createApp, createRouter } from 'h3' From 799d92eac1c1bedfa8b859ddcdaed5dc0cddfcb5 Mon Sep 17 00:00:00 2001 From: pooya parsa Date: Thu, 7 Apr 2022 23:24:35 +0200 Subject: [PATCH 08/10] Update docs/content/2.guide/2.features/9.api-routes.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Sébastien Chopin --- docs/content/2.guide/2.features/9.api-routes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md index ff1b5ee618f..4d7834556fa 100644 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ b/docs/content/2.guide/2.features/9.api-routes.md @@ -2,7 +2,7 @@ Nuxt will automatically register files in the `/server/api` directory to create API endpoints. -To handle requests, each file should export a default function (an [unjs/h3](https://github.com/unjs/h3) event handler or classic `(req, res) => {})`. The handler can directly return JSON data, a Promise or use `event.res.end()` to send response by itself. +To handle requests, each file should export a default function (an [unjs/h3](https://github.com/unjs/h3) event handler or classic `(req, res) => {}`. The handler can directly return JSON data, a `Promise` or use `event.res.end()` to send response by itself. Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions). From 0773954b2dcf5036e5bc11abd789f608c1a3a66a Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sat, 9 Apr 2022 13:33:42 +0200 Subject: [PATCH 09/10] improcements and merge into generic server routes --- .../2.guide/2.features/9.api-routes.md | 108 ----------- .../2.guide/2.features/9.server-routes.md | 174 ++++++++++++++++++ .../3.directory-structure/13.server.md | 102 +--------- 3 files changed, 175 insertions(+), 209 deletions(-) delete mode 100644 docs/content/2.guide/2.features/9.api-routes.md create mode 100644 docs/content/2.guide/2.features/9.server-routes.md diff --git a/docs/content/2.guide/2.features/9.api-routes.md b/docs/content/2.guide/2.features/9.api-routes.md deleted file mode 100644 index 4d7834556fa..00000000000 --- a/docs/content/2.guide/2.features/9.api-routes.md +++ /dev/null @@ -1,108 +0,0 @@ -# API Routes - -Nuxt will automatically register files in the `/server/api` directory to create API endpoints. - -To handle requests, each file should export a default function (an [unjs/h3](https://github.com/unjs/h3) event handler or classic `(req, res) => {}`. The handler can directly return JSON data, a `Promise` or use `event.res.end()` to send response by itself. - -Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions). - -## Route Parameter - -For ease of use, routes that are dependent on a parameter can specify the parameter within brackets in the file name `/api/hello/[parameter].ts`. - -```ts [/server/api/hello/[name].ts] -export default defineEventHandler(event => { - return `Hello, ${event.context.params.name}!` -}) -``` - -## Method Matching - -Routes can be suffixed with `.get`, `.post`, `.put`, `.delete` to match a [supported HTTP Method](https://github.com/unjs/nitro/blob/main/src/runtime/virtual/server-handlers.d.ts#L7). - -```ts [/server/api/test.post.ts] -export default defineEventHandler(() => 'Test post handler') -``` - -Given the example above, the `test` route will be declared as a `POST` route. - -## Catch-all route - -A catch all route can be defined by creating a file in the `api` directory with the name `[...].ts`. This route will be triggered for all requests that do not match any other route. - -This is useful for special use cases as well as fallback error handling. - -```ts [/server/api/[...].ts] -export default defineEventHandler(event => `Default page`) -``` - -## Examples - -### Hello World - -```ts [/server/api/hello.ts] -export default defineEventHandler(() => '

Hello World

') -``` - -### POST Request - - - - -```ts [/server/api/hello.ts] -export default defineEventHandler(async (event) => { - const body = await useBody(event) // only for POST | PUT | PATCH | DELETE requests - - return { body } -}) -``` - - - - -```ts [/server/api/hello.post.ts] -export default defineEventHandler(() => '

Hello World

') -``` - -
-
- -### Using Router - -```ts [/server/api/hello.ts] -import { createApp, createRouter } from 'h3' - -const app = createApp() -const router = createRouter() - -app.use(router) - -router.get('/', () => 'Hello World') - -export default app -``` - -### Access Request Data - -```ts -export default defineEventHandler(async (event) => { - const params = event.context.params; - const body = await useBody(event) // only for POST | PUT | PATCH | DELETE requests - const cookies = useCookies(event) - - return { params, body, cookies }; -}); -``` - -### Server Routes - -It's now possible to register server handlers without the `/api` prefix, by creating a `server/routes` directory. All handlers in the `routes` directory will be registered as server routes and can be directly requested without the `/api` prefix. - -```ts [/server/routes/hello.ts] -export default defineEventHandler(() => 'Hello World!') -``` - -Given the example above, the `/hello` route will be accessible at . - -::ReadMore{link="https://github.com/unjs/nitro#routes-and-api-routes" title="Nitro Routes"} -:: diff --git a/docs/content/2.guide/2.features/9.server-routes.md b/docs/content/2.guide/2.features/9.server-routes.md new file mode 100644 index 00000000000..93de4ceb2ba --- /dev/null +++ b/docs/content/2.guide/2.features/9.server-routes.md @@ -0,0 +1,174 @@ +# Server Routes + +Nuxt automatically scans files inside the `~/server/api`, `~/server/routes`, and `~/server/middleware` directories to register API and server handlers with HMR support. + +Each file should export a default function defined with `defineEventHandler()`. + +The handler can directly return JSON data, a `Promise` or use `event.res.end()` to send response. + +::ReadMore{link="https://nitro.unjs.io/guide/routing.html" title="Nitro Route Handling Docs"} +:: + +## Usage Example + +Create a new file in `server/api/hello.ts`: + +```ts [/server/api/hello.ts] +export default defineEventHandler((event) => { + return { + api: 'works' + } +}) +``` + +You can now universally call this API using `await $fetch('/API/hello')`. + +## Server Routes + +Files inside the `~/server/api` are automatically prefixed with `/api` in their route. +For adding server routes without `/api` prefix, you can instead put them into `~/server/routes` directory. + +**Example:** + +```ts [/server/routes/hello.ts] +export default defineEventHandler(() => 'Hello World!') +``` + +Given the Example above, the `/hello` route will be accessible at . + +## Server Middleware + +Nuxt will automatically read in any file in the `~/server/middleware` to create server middleware for your project. + +Middleware handlers will run on every request before any other server route to add check and some headers, log requests, or extend the event's request object. + +::alert{type=warning} +Middleware handlers should not return anything (nor close or respond to the request) and only inspect or extend the request context or throw an error. +:: + + +**Examples:** + +```ts [/server/middleware/log.ts] +export default defineEventHandler((event) => { + console.log('New request: ' + event.req.url) +}) +``` + +```ts [/server/middleware/auth.ts] +export default defineEventHandler((event) => { + event.context.auth = { user: 123 } +}) +``` + +## Matching Route Parameters + +Server routes can use dynamic parameters within brackets in the file name like `/api/hello/[:name].ts` and accessed via `event.context.params`. + +**Example:** + +```ts [/server/api/hello/[name].ts] +export default defineEventHandler(event => `Hello, ${event.context.params.name}!`) +``` + +You can now universally call this API using `await $fetch('/API/hello/nuxt')` and get `Hello, nuxt!`. + +## Matching HTTP Method + +Handle file names can be suffixed with `.get`, `.post`, `.put`, `.delete`, ... to match request's [HTTP Method](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods). + +```ts [/server/api/test.get.ts] +export default defineEventHandler(() => 'Test get handler') +``` + +```ts [/server/api/test.post.ts] +export default defineEventHandler(() => 'Test post handler') +``` + +Given the Example above, fetching `/test` with: + +- **GET** method: Returns `Test get handler` +- **POST** method: Returns `Test post handler` +- Any other method: Returns 404 error + +## Catch-all route + +Catch-all routes are helpful for fallback route handling. For Example, creating a file in the `~/server/api/foo/[...].ts` will register a catch-all route for all requests that do not match any route handler, such as `/api/foo/bar/baz`. + +**Examples:** + +```ts [/server/api/foo/[...].ts] +export default defineEventHandler(() => `Default foo handler`) +``` + +```ts [/server/api/[...].ts] +export default defineEventHandler(() => `Default api handler`) +``` + +## Handling Requests with Body + +```ts [/server/api/submit.post.ts] +export default defineEventHandler(async (event) => { + const body = await useBody(event) + return { body } +}) +``` + +You can now universally call this API using `$fetch('/api/submit', { method: 'post', body: { test: 123 } })`. + +::alert{type=warning title=Attention} +We are using `submit.post.ts` in the filename only to match requests with `POST` method that can accept the request body. When using `useBody` within a GET request, `useBody` will throw a `405 Method Not Allowed` HTTP error. +:: + +## Access Request Cookies + +```ts +export default defineEventHandler((event) => { + const cookies = useCookies(event) + return { cookies } +}) +``` + +## Using a nested router + +```ts [/server/api/hello.ts] +import { createRouter } from 'h3' + +const router = createRouter() + +router.get('/', () => 'Hello World') + +export default router +``` + +## Return a legacy handler or middleware + +```ts [/server/api/legacy.ts] +export default (req, res) => { + res.end('Legacy handler') +} +``` + +::alert{type=warning} +Legacy support is possible using [unjs/h3](https://github.com/unjs/h3) but it adviced to avoid legacy handlers as much as you can. +:: + +```ts [/server/middleware/legacy.ts] +export default (req, res, next) => { + console.log('Legacy middleware') + next() +} +``` + +::alert{type=warning} +Never combine `next()` callback with a legacy middleware that is `async` or returns a `Promise`! +:: + +## Server Utils + +Server routes are powered by [unjs/h3](https://github.com/unjs/h3) which comes with a handy set of helpers. + +::ReadMore{link="https://www.jsdocs.io/package/h3#package-index-functions" title="Available H3 Request Helpers"} +:: + +You can add more helpers by yourself inside the `~/server/utils` directory. diff --git a/docs/content/2.guide/3.directory-structure/13.server.md b/docs/content/2.guide/3.directory-structure/13.server.md index a19d6d9f3f8..57818b49c09 100644 --- a/docs/content/2.guide/3.directory-structure/13.server.md +++ b/docs/content/2.guide/3.directory-structure/13.server.md @@ -4,104 +4,4 @@ title: server head.title: Server directory --- -# Server directory - -Nuxt uses the `server/` directory to create any backend logic for your application. It supports HMR and powerful features. - -The `server/` directory contains API endpoints and server middleware for your project. - -## API Routes - -Nuxt will automatically read in any files in the `~/server/api` directory to create API endpoints. - -Each file should export a default function that handles API requests. It can return a promise or JSON data directly (or use `res.end()`). - -### Examples - -#### Hello world - -```js [server/api/hello.ts] -export default (req, res) => 'Hello World' -``` - -See the result on . - -#### Async function - -```js [server/api/async.ts] -export default async (req, res) => { - await someAsyncFunction() - - return { - someData: true - } -} -``` - -**Example:** Using Node.js style - -```ts [server/api/node.ts] -import type { IncomingMessage, ServerResponse } from 'http' - -export default async (req: IncomingMessage, res: ServerResponse) => { - res.statusCode = 200 - res.end('Works!') -} -``` - -#### Accessing req data - -```js -import { useBody, useCookies, useQuery } from 'h3' - -export default async (req, res) => { - const query = useQuery(req) - const body = await useBody(req) // only for POST | PUT | PATCH | DELETE requests - const cookies = useCookies(req) - - return { query, body, cookies } -} -``` - -Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions). - -## Server Middleware - -Nuxt will automatically read in any files in the `~/server/middleware` to create server middleware for your project. - -These files will be run on every request, unlike [API routes](#api-routes) that are mapped to their own routes. This is typically so you can add a common header to all responses, log responses or modify the incoming request object for later use in the request chain. - -Each file should export a default function that will handle a request. - -```js -export default async (req, res) => { - req.someValue = true -} -``` - -There is nothing different about the `req`/`res` objects, so typing them is straightforward. - -```ts -import type { IncomingMessage, ServerResponse } from 'http' - -export default async (req: IncomingMessage, res: ServerResponse) => { - req.someValue = true -} -``` - -To pass the request deeper into the application, you can `return` inside the function: - -```js -export default async (req, res) => { - const isNotHandledByThisMiddleware = req.url.includes('/some-unhandled-url-path/') - if(isNotHandledByThisMiddleware) { - return - } - - // Actual logic here -} -``` - -::alert{type=info icon=🔎} -Find more information about custom middleware in the documentation for [nuxt.config.js](/guide/directory-structure/nuxt.config#servermiddleware) -:: +::ReadMore{link="/guide/features/server-routes"} From 30a5c3cbcbf1751c764f4dfe98e2356b944a4c0d Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sat, 9 Apr 2022 13:35:35 +0200 Subject: [PATCH 10/10] lint --- docs/content/2.guide/2.features/9.server-routes.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/content/2.guide/2.features/9.server-routes.md b/docs/content/2.guide/2.features/9.server-routes.md index 93de4ceb2ba..8c5d25c6ada 100644 --- a/docs/content/2.guide/2.features/9.server-routes.md +++ b/docs/content/2.guide/2.features/9.server-routes.md @@ -46,7 +46,6 @@ Middleware handlers will run on every request before any other server route to a Middleware handlers should not return anything (nor close or respond to the request) and only inspect or extend the request context or throw an error. :: - **Examples:** ```ts [/server/middleware/log.ts]