Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(routing): add middleware section #1307

Merged
merged 6 commits into from
Aug 6, 2023
Merged
Changes from all 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
72 changes: 72 additions & 0 deletions docs/content/1.guide/3.routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,75 @@ export default defineNuxtConfig({
})
```
::

## Route Middleware

Nitro route middleware can hook into the request lifecycle.

::alert{type=primary}
A middleware can modify the request before it is processed, not after.
::

Middleware are auto-registered within the `middleware/` directory.

```md
routes/
hello.ts
middleware/
auth.ts
logger.ts
...
nitro.config.ts
```

### Simple Middleware

Middleware are defined exactly like route handlers with the only exception that they should not return anything.

```ts [middleware/auth.ts]
export default defineEventHandler((event) => {
// Extends or modify the event
event.context.user = { name: 'Nitro' }
})
```

::alert
Returning anything from a middleware will close the request and should be avoided!
::

### Execution Order

Middleware are executed in directory listing order.

```md
middleware/
auth.ts <-- First
logger.ts <-- Second
... <-- Third
```

Prefix middleware with a number to control their execution order.

```md
middleware/
1.logger.ts <-- First
2.auth.ts <-- Second
3.... <-- Third
```

### Request Filtering

Middleware are executed on every request.

Apply custom logic to scope them to specific conditions.

For example, you can use the URL to apply a middleware to a specific route:

```ts [middleware/auth.ts]
export default defineEventHandler((event) => {
// Will only execute for /auth route
if (getRequestURL(event).startsWith('/auth')) {
event.context.user = { name: 'Nitro' }
}
})
```