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: add object syntax for event handler #2091

Merged
merged 6 commits into from
Jan 23, 2024
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
38 changes: 38 additions & 0 deletions docs/content/1.guide/3.routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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!**
::
Expand Down Expand Up @@ -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.