Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

docs: add server routes documentation #4174

Merged
merged 18 commits into from
Apr 9, 2022
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 103 additions & 4 deletions docs/content/2.guide/2.features/9.api-routes.md
Original file line number Diff line number Diff line change
@@ -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 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()`.
Diizzayy marked this conversation as resolved.
Show resolved Hide resolved

Learn more about [h3 methods](https://www.jsdocs.io/package/h3#package-index-functions).
Diizzayy marked this conversation as resolved.
Show resolved Hide resolved

## 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 => {
Diizzayy marked this conversation as resolved.
Show resolved Hide resolved
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
Diizzayy marked this conversation as resolved.
Show resolved Hide resolved

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 eventHandler(event => `Default page`)
```

## Examples
Diizzayy marked this conversation as resolved.
Show resolved Hide resolved

### Hello World

```ts [/server/api/hello.ts]
export default eventHandler(() => '<h1>Hello World</h1>')
```

### POST Request

<code-group>
<code-block label="Basic" active>

```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 }
})
```

</code-block>
<code-block label="Method Matching">

```ts [/server/api/hello.post.ts]
export default defineEventHandler(() => '<h1>Hello World</h1>')
```

</code-block>
</code-group>

### 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) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's not advocate this or if doing, mentioning is mainly for supporting legacy middleware and advanced use. h3 is dropping node dependency progressively (unjs/h3#73)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

taking that into consideration, do you think the best forward thinking resolve would just be to avoid mentioning it altogether?

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);
Diizzayy marked this conversation as resolved.
Show resolved Hide resolved

return { params, body, cookies };
});
```