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: onRoute hooks in plugins #4285

Merged
merged 5 commits into from Sep 20, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
43 changes: 43 additions & 0 deletions docs/Guides/Plugins-Guide.md
Expand Up @@ -308,6 +308,49 @@ fastify.get('/plugin2', (request, reply) => {
```
Now your hook will run just for the first route!

An alternative approach is to make use of the [onRoute hook](https://www.fastify.io/docs/latest/Reference/Hooks/#onroute)
philsch marked this conversation as resolved.
Show resolved Hide resolved
to customize application routes dynamically from inside the plugin. Every time a new route gets registered, you can read
and modify the route options, for example
based on a [route config option](https://www.fastify.io/docs/latest/Reference/Routes/#routes-options):

```js
fastify.register((instance, opts, done) => {
instance.decorate('util', (request, key, value) => { request[key] = value })

function handler(request, reply, done) {
instance.util(request, 'timestamp', new Date())
done()
}

instance.addHook('onRoute', (routeOptions) => {
if (routeOptions.config && routeOptions.config.useUtil === true) {
// set or add our handler to the route preHandler hook
if (!routeOptions.preHandler) {
routeOptions.preHandler = [handler]
return
}
if (Array.isArray(routeOptions.preHandler)) {
routeOptions.preHandler.push(handler)
return
}
routeOptions.preHandler = [routeOptions.preHandler, handler]
}
})

fastify.get('/plugin1', {config: {useUtil: true}}, (request, reply) => {
reply.send(request)
})

fastify.get('/plugin2', (request, reply) => {
reply.send(request)
})

done()
})
```

This variant becomes extremely useful if you plan to distribute your plugin, as described in the next section.

As you probably noticed by now, `request` and `reply` are not the standard
Nodejs *request* and *response* objects, but Fastify's objects.

Expand Down