Fastify JWT Auth Guard Decorator
Protect Fastify routes with the JWT plugin via preHandler guards, verifying tokens once and exposing typed claims to handlers.
Code
import Fastify from 'fastify';
import jwt from '@fastify/jwt';
interface TokenClaims {
sub: string;
role: 'admin' | 'editor' | 'viewer';
}
declare module 'fastify' {
interface FastifyRequest {
user: TokenClaims;
}
}
const app = Fastify({ logger: true });
await app.register(jwt, {
secret: process.env.JWT_SECRET ?? 'dev-secret-change-me',
sign: { expiresIn: '15m' },
});
function requireRole(...roles: TokenClaims['role'][]) {
return async (req: Fastify.FastifyRequest, reply: Fastify.FastifyReply) => {
try {
await req.jwtVerify<TokenClaims>();
} catch {
return reply.code(401).send({ error: 'invalid or expired token' });
}
if (!roles.includes(req.user.role)) {
return reply.code(403).send({ error: 'insufficient role' });
}
};
}
app.get('/me', { preHandler: requireRole('viewer', 'editor', 'admin') },
async (req) => ({ userId: req.user.sub, role: req.user.role }),
);
app.post('/admin/purge', { preHandler: requireRole('admin') },
async (req, reply) => reply.code(202).send({ purged: true, by: req.user.sub }),
);
app.inject({
method: 'GET',
url: '/me',
headers: { authorization: 'Bearer ' + app.jwt.sign({ sub: 'u-1', role: 'viewer' }) },
}).then((res) => console.log('status:', res.statusCode));How it works
Under the hood: the function requireRole.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Configuration comes from the environment — it reads JWT_SECRET, so the same code switches behavior between environments without edits.
What to watch for
- Plan for an install step:
fastifyand@fastify/jwtare a real dependency, resolved by the package manager.
Using it
The primary signature is function requireRole(...roles: TokenClaims['role'][])
Running the file prints labeled results such as status: — each operation’s effect is visible in the output.
Key statements
return async (req: Fastify.FastifyRequest, reply: Fastify.FastifyReply) => {
try {
await req.jwtVerify<TokenClaims>();
} catch {
return reply.code(401).send({ error: 'invalid or expired token' });
}
if (!roles.includes(req.user.role)) {
return reply.code(403).send({ error: 'insufficient role' });
}
};
await app.register(jwt, {
secret: process.env.JWT_SECRET ?? 'dev-secret-change-me',
sign: { expiresIn: '15m' },
});
Interactive Tools for This Topic
Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.JWT Expiry CalculatorDecode a JWT payload and convert its exp, iat, and nbf claims into UTC ISO timestamps, with an expired-or-valid verdict.JWT Token DecoderDecode JSON Web Token (JWT) headers and payloads safely in the browser. Inspect expiration, issuer, and claims without sending tokens to any external server.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
FAQ
- Does this require external packages?
- Yes — `fastify` and `@fastify/jwt`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.