diff --git a/docs/content/1.guide/3.routing.md b/docs/content/1.guide/3.routing.md index 4380a9c163..983e27b9f0 100644 --- a/docs/content/1.guide/3.routing.md +++ b/docs/content/1.guide/3.routing.md @@ -221,6 +221,8 @@ export default defineEventHandler((event) => { }) ``` +Middleware in `middleware/` directory are automatically registered for all routes. If you want to register a middleware for a specific route, see [Object Syntax Event Handler](#object-syntax-event-handler). + ::alert Returning anything from a middleware will close the request and should be avoided! Any returned value from middleware will be the response and further code will not be executed however **this is not recommended to do!** :: @@ -261,3 +263,39 @@ export default defineEventHandler((event) => { } }) ``` + +## Object Syntax Event Handler + +Since H3@1.8, you can use a new object syntax to define event handler. + +::alert{type=primary} +Read the announcement on the [UnJS blog](https://unjs.io/blog/2023-08-15-h3-towards-the-edge-of-the-web#object-syntax-event-handlers). +:: + +You can start by defining middleware in a file like `utils/auth.ts` to be able to auto-import them in your routes: + +```ts [utils/auth.ts] +export const auth = defineRequestMiddleware((event) => { + event.context.auth = { name: 'admin' } +}) +``` + +```ts [utils/log.ts] +export const log = defineRequestMiddleware((event) => { + console.log(event) +}) +``` + +Then, you can use them in your routes: + +```ts [routes/hello.ts] +export default eventHandler({ + onRequest: [auth], + onBeforeResponse: [log], + async handler(event) { + return `Hello ${event.context.auth?.name || 'Guest'}` + }, +}) +``` + +This synxtax allows you to order and define middleware before the handler and before the response.