Skip to content

Commit

Permalink
docs: update the routing page (#2085)
Browse files Browse the repository at this point in the history
  • Loading branch information
Barbapapazes authored Jan 17, 2024
1 parent cdb0ee4 commit 98cae74
Showing 1 changed file with 74 additions and 34 deletions.
108 changes: 74 additions & 34 deletions docs/content/1.guide/3.routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,22 @@ icon: ri:direction-line

# Routing

Nitro support filesystem routing as well as defining route rules for maximum flexibility and performance.
Nitro support filesystem routing to define handler as well as defining route rules for maximum flexibility and performance.

A handle is a function that will be binded to a route and executed when the route is matched by the router for an incoming request.

## Filesystem Routing

Nitro supports file-based routing for your API routes.
Nitro supports file-based routing for your API routes (file are atomatically mapped to [unjs/h3](https://github.com/unjs/h3) routes). Defining a route is as simple as creating a file inside the `api/` or `routes/` directory.

Handler files inside `api/` and `routes/` directory will be automatically mapped to [unjs/h3](https://github.com/unjs/h3) routes.
You can only define one handler per files and you can [append the HTTP method](#specific-request-method) to the filename to define a specific request method.

```md
api/
test.ts <-- /api/test
routes/
hello.ts <-- /hello
hello.get.ts <-- GET /hello
hello.post.ts <-- POST /hello
nitro.config.ts
```

Expand All @@ -32,51 +35,81 @@ If you are using [Nuxt](https://nuxt.com), move the `api/` and `routes/` inside

### Simple route

```ts
// api/hello.ts
First, create a file in `routes/` or `api/` directory. The filename will be the route path.

Then, export a function wrapped in `defineEventHandler` that will be executed when the route is matched.

```ts [/api/test.ts]
export default defineEventHandler(() => {
return { hello: 'world' }
return { hello: 'API' }
})
```

You can now universally call this API using `await $fetch('/api/hello')`.
You do not need to import `defineEventHandler` as it is automatically imported thanks to [auto-import feature](/auto-imports).

### Route with params

```js
// routes/hello/[name].ts
export default defineEventHandler(event => `Hello ${event.context.params.name}!`)
#### Single param

To define a route with params, use the `[<param>]` syntax where `<param>` is the name of the param. The param will be available in the `event.context.params` object or using the `getRouteParam` utility from [unjs/h3](https://h3.unjs.io).

```ts [/hello/[name].ts]
export default defineEventHandler(event => {
const name = getRouteParam(event, 'name')

return `Hello ${name}!`
})
```

::code-group
```md [/hello/nitro]
Call the route with the param `/hello/nitro`, you will get:

```txt [Response]
Hello nitro!
```
::

To include the `/`, use `[...name].ts`:
#### Multiple params

You can define multiple params in a route using `[<param1>]/[<param2>]` syntax where each param is a folder. You **cannot** define multiple params in a single filename of folder.

```ts [/hello/[name]/[age].ts]
export default defineEventHandler(event => {
const name = getRouteParam(event, 'name')
const age = getRouteParam(event, 'age')

```js
// routes/hello/[...name].ts
export default defineEventHandler(event => `Hello ${event.context.params.name}!`)
return `Hello ${name}! You are ${age} years old.`
})
```

::code-group
```md [/hello/nitro/is/hot]
#### Catch all params

You can capture all the remaining parts of a URL using `[...<param>]` syntax. This will include the `/` in the param.

```ts [/hello/[...name].ts]
export default defineEventHandler(event => {
const name = getRouteParam(event, 'name')

return `Hello ${name}!`
})
```

Call the route with the param `/hello/nitro/is/hot`, you will get:

```txt [Response]
Hello nitro/is/hot!
```
::

### Specific request method

API route with a specific HTTP request method (get, post, put, delete, options and so on).
You can append the HTTP method to the filename to force the route to be matched only for a specific HTTP request method, for example `hello.get.ts` will only match for `GET` requests. You can use any HTTP method you want.

::code-group
```js [GET]
// routes/users/[id].get.ts
export default defineEventHandler(async (event) => {
const { id } = event.context.params
// TODO: fetch user by id
const id = getRouteParam(event, 'id')

// Do something with id

return `User profile!`
})
```
Expand All @@ -85,36 +118,43 @@ export default defineEventHandler(async (event) => {
// routes/users.post.ts
export default defineEventHandler(async event => {
const body = await readBody(event)
// TODO: Handle body and add user

// Do something with body like saving it to a database

return { updated: true }
})
```
::

Check out [h3 JSDocs](https://www.jsdocs.io/package/h3#package-index-functions) for all available utilities like `readBody`.
Check out [h3 JSDocs](https://www.jsdocs.io/package/h3) for all available utilities like `getRouteParam` or `readBody`.

### Catch all route

```js
// routes/[...].ts
export default defineEventHandler(event => `Default page`)
You can create a special route that will match all routes that are not matched by any other route. This is useful for creating a default route.

To create a catch all route, create a file named `[...].ts` in the `routes/` or `api/` directory or in any subdirectory.

```ts [/routes/[...].ts]
export default defineEventHandler(event => {
const url = getRequestURL(event)

return `Hello ${url}!`
})
```

## Route Rules

Nitro allows you to add logic at the top-level of your configuration, useful for redirecting, proxying, caching and adding headers to routes.
Nitro allows you to add logic at the top-level for each route of your configuration. It can be used for redirecting, proxying, caching and adding headers to routes.

It is a map from route pattern (following [unjs/radix3](https://github.com/unjs/radix3#route-matcher)) to route options.

When `cache` option is set, handlers matching pattern will be automatically wrapped with `defineCachedEventHandler`.

See the [Cache API](/guide/cache) for all available cache options.
When `cache` option is set, handlers matching pattern will be automatically wrapped with `defineCachedEventHandler`. See the [guide cache](/guide/cache) to learn more about this function.

::alert
`swr: true|number` is shortcut for `cache: { swr: true, maxAge: number }`
::

**Example:**
You can set route rules in `nitro.config.ts` using the `routeRules` option.

::code-group
```ts [nitro.config.ts]
Expand Down

0 comments on commit 98cae74

Please sign in to comment.