Add a Fastify hook for authentication
Reject unauthenticated requests early in Fastify 5 with an onRequest hook, scoped to a plugin so public routes stay open.
Authentication has to run before validation and parsing. The onRequest hook is the first one in the request lifecycle.
export default async function privatePlugin(app) {
app.addHook('onRequest', async (request, reply) => {
const token = request.headers.authorization?.replace('Bearer ', '');
if (token !== process.env.API_TOKEN) {
return reply.code(401).send({ error: 'Unauthorized' });
}
});
app.get('/me', async () => ({ name: 'Ada' }));
}import Fastify from 'fastify';
import privatePlugin from './src/plugins/private.js';
const app = Fastify();
app.get('/health', async () => ({ status: 'ok' }));
app.register(privatePlugin, { prefix: '/private' });
await app.listen({ port: 3000 });GET /health -> 200 {"status":"ok"}
GET /private/me -> 401 {"error":"Unauthorized"}
GET /private/me (Authorization: Bearer <token>) -> 200 {"name":"Ada"}A hook added inside a plugin applies only to that plugin's routes and its children, so /health is untouched. In an async hook, send the reply and return it to stop the lifecycle, as the Hooks reference describes. Returning nothing lets the request continue.
Compare tokens in constant time in real code, for example with crypto.timingSafeEqual, and prefer a maintained plugin such as @fastify/jwt for token verification.