@fastify/jwt
JWT authentication plugin for Fastify — sign, verify, and decode tokens with a decorator-based API that integrates with Fastify's request lifecycle.
@fastify/jwt
FastifyJWT authentication plugin for Fastify — sign, verify, and decode tokens with a decorator-based API that integrates with Fastify's request lifecycle.
Fit
Bundle (gzip)
38.4 kB
133.1 kB raw
Install size includes transitive dependencies. Bundle size is gzipped browser payload.
Freshness
The Problem
Adding JWT authentication to Fastify routes requires integrating a JWT library with Fastify's plugin system, hooks, and request decorators. Rolling this manually risks inconsistent error handling and bypassed verification.
What It Does
@fastify/jwt decorates fastify with sign() and verify() methods and adds request.jwtVerify() for use in route handlers or hooks. A preHandler hook can enforce authentication on entire route groups. It supports symmetric and asymmetric algorithms and token refresh patterns.
Installation
npm install @fastify/jwtUsage Example
import fastify from 'fastify';
import jwt from '@fastify/jwt';
const app = fastify();
await app.register(jwt, { secret: process.env.JWT_SECRET! });
// Protect a route
app.addHook('onRequest', async (request, reply) => {
try { await request.jwtVerify(); }
catch { reply.send({ error: 'Unauthorized' }); }
});
app.post('/login', async (request, reply) => {
const { email } = request.body as { email: string };
const token = await reply.jwtSign({ email }, { expiresIn: '7d' });
return { token };
});Related packages
Auto-load Fastify plugins from a directory — organize routes and plugins as files and let the framework discover them automatically.
@fastify/cookieFastifyPlugin for Fastify that adds support for reading and setting cookies, including signed cookies.
@fastify/corsFastifyCORS plugin for Fastify — configure cross-origin resource sharing with full support for preflight requests and dynamic origins.
@fastify/helmetFastifySecurity headers plugin for Fastify — sets HTTP headers that protect against common web vulnerabilities like XSS, clickjacking, and MIME sniffing.
@fastify/multipartFastifyMultipart form data / file upload plugin for Fastify — stream files directly to storage without buffering in memory.