Skip to content

Commit

Permalink
merge to routing
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 6, 2023
1 parent 387dd3d commit e13121e
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 75 deletions.
74 changes: 74 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,77 @@ 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' }
}
})
```
75 changes: 0 additions & 75 deletions docs/content/1.guide/4.middleware.md

This file was deleted.

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit e13121e

Please sign in to comment.