Skip to content

Commit

Permalink
docs: onRoute hooks in plugins (#4285)
Browse files Browse the repository at this point in the history
* docs: onRoute hooks in plugins

* relative links

* formatting

* linting

* Update docs/Guides/Plugins-Guide.md

Co-authored-by: Frazer Smith <frazer.dev@outlook.com>

Co-authored-by: Frazer Smith <frazer.dev@outlook.com>
  • Loading branch information
philsch and Fdawgs committed Sep 20, 2022
1 parent aa84678 commit d1a3845
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions docs/Guides/Plugins-Guide.md
Expand Up @@ -308,6 +308,50 @@ 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](../Reference/Hooks.md#onroute)
to customize application routes dynamically from inside the plugin. Every time
a new route is registered, you can read and modify the route options. For example,
based on a [route config option](../Reference/Routes.md#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

0 comments on commit d1a3845

Please sign in to comment.