diff --git a/docs/content/1.guide/3.routing.md b/docs/content/1.guide/3.routing.md index 4871c1ac41..07c63a2233 100644 --- a/docs/content/1.guide/3.routing.md +++ b/docs/content/1.guide/3.routing.md @@ -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' } + } +}) +```