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

update onRoute hook docs #4322

Merged
merged 2 commits into from Oct 6, 2022
Merged
Changes from all commits
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
27 changes: 27 additions & 0 deletions docs/Reference/Hooks.md
Expand Up @@ -449,6 +449,33 @@ fastify.addHook('onRoute', (routeOptions) => {
})
```

If you want to add more routes within an onRoute hook, you have to tag these
routes properly. If you don't, the hook will run into an infinite loop. The
recommended approach is shown below.

```js
const kRouteAlreadyProcessed = Symbol('route-already-processed')

fastify.addHook('onRoute', function (routeOptions) {
const { url, method } = routeOptions

const isAlreadyProcessed = (routeOptions.custom && routeOptions.custom[kRouteAlreadyProcessed]) || false

if (!isAlreadyProcessed) {
this.route({
url,
method,
custom: {
[kRouteAlreadyProcessed]: true
},
handler: () => {}
})
}
})
```

For more details, see this [issue](https://github.com/fastify/fastify/issues/4319).

### onRegister
<a id="on-register"></a>

Expand Down