Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Aug 6, 2023
1 parent 5558a13 commit 387dd3d
Showing 1 changed file with 15 additions and 25 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@
icon: ri:shield-user-line
---

# Middlewares
# Middleware

Nitro middlewares can hook into the request lifecycle.
Nitro middleware can hook into the request lifecycle.

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

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

```md
routes/
Expand All @@ -22,9 +22,9 @@ middleware/
nitro.config.ts
```

## Simple middleware
## Simple Middleware

Middlewares are defined exactly like route handlers.
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) => {
Expand All @@ -34,12 +34,12 @@ export default defineEventHandler((event) => {
```

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

## Execution order
## Execution Order

Middlewares are executed in directory listing order.
Middleware are executed in directory listing order.

```md
middleware/
Expand All @@ -48,34 +48,24 @@ middleware/
... <-- Third
```

Prefix middlewares with a number to control their execution order.
Prefix middleware with a number to control their execution order.

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

Middlewares can be grouped in subdirectories.

```md
middlewares/
auth/
index.ts
...
logger/
index.ts
...
```
## Request Filtering

## Request filtering
Middleware are executed on every request.

Middlewares 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 [middlewares/auth.ts]
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')) {
Expand Down

0 comments on commit 387dd3d

Please sign in to comment.