onRoute hook

Runs synchronously whenever a route is registered, allowing route option mutation.

Since Fastify 5 Spec ↗

Syntax

app.addHook('onRoute', (routeOptions) => {})

Parameters

NameTypeRequiredDescription
routeOptions RouteOptions No The mutable options of the route being registered.

Returns

void — Synchronous; mutate routeOptions in place.

Examples

import Fastify from 'fastify';

const app = Fastify();

app.addHook('onRoute', (routeOptions) => {
  if (routeOptions.config?.auth) {
    routeOptions.preHandler = [
      ...[].concat(routeOptions.preHandler ?? []),
      authGuard,
    ];
  }
});

Notes

Synchronous and encapsulated to the scope where it is added. Commonly used to attach hooks or defaults based on per-route config, or to build documentation from registered routes.