Lesson 16 / 30
Authentication with JWT
Implement token-based authentication in Fastify.
JWT flow in Fastify
- Client sends credentials to
/login. 2) Server verifies and issues a JWT. 3) Client includes token inAuthorization: Bearer <token>. 4) A preHandler hook verifies the token before routes run.
Login and token generation
Create a login route that signs and returns a JWT.
import jwt from '@fastify/jwt';
await fastify.register(jwt, { secret: process.env.JWT_SECRET });
fastify.post('/login', async (req) => {
const { email, password } = req.body;
// Verify credentials (your logic here)
const user = await verifyUser(email, password);
if (!user) {
return reply.status(401).send({ error: 'Invalid credentials' });
}
const token = fastify.jwt.sign({ sub: user.id, email: user.email });
return { token };
});Protecting routes
Use a preHandler to verify tokens before route execution.
async function authenticate(request, reply) {
try {
await request.jwtVerify();
} catch (err) {
reply.status(401).send({ error: 'Unauthorized' });
}
}
fastify.get('/me', { preHandler: [authenticate] }, async (req) => {
return { userId: req.user.sub, email: req.user.email };
});