Skip to content
jshacks.dev
Frameworks

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.

1 min read
Summarize in AI

Authentication has to run before validation and parsing. The onRequest hook is the first one in the request lifecycle.

src/plugins/private.jsJavaScript
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' }));
}
server.jsJavaScript
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 });
Text
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.

Also inNode.js
Taggedfastify 5
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.