@fastify/jwt Plugin
const Fastify = require('fastify');\n\nconst app = Fastify({ logger: true });\n\n// Register JWT plugin\nawait app.register(require('@fastify/jwt'), {\n secret: process.env.JWT_SECRET || 'my-super-secret-key-change-in-production',\n});\n\n// Add auth decorator\napp.decorate('authenticate', async function(request, reply) {\n try {\n await request.jwtVerify();\n } catch (err) {\n reply.send(err);\n }\n});\n\n// Public route\napp.post('/login', async (request, reply) => {\n const { email, password } = request.body;\n\n // Verify credentials...\n const user = await db.users.findByEmail(email);\n if (!user || !(await bcrypt.compare(password, user.password))) {\n return reply.code(401).send({ error: 'Invalid credentials' });\n }\n\n // Generate token\n const token = app.jwt.sign({\n userId: user.id,\n role: user.role,\n }, { expiresIn: '1h' });\n\n return { token };\n});\n\n// Protected route\napp.get('/profile', {\n preHandler: [app.authenticate],\n}, async (request) => {\n const { userId } = request.user;\n return db.users.findById(userId);\n});
Examples
const Fastify = require('fastify');
const app = Fastify({ logger: true });
async function build() {
// Register JWT
await app.register(require('@fastify/jwt'), {
secret: 'change-me-in-production',
});
// Decorate with auth check
app.decorate('auth', async (request, reply) => {
try {
await request.jwtVerify();
} catch (err) {
reply.code(401).send({ error: 'Unauthorized' });
}
});
// Login route
app.post('/login', async (request, reply) => {
const { username, password } = request.body;
// Mock user verification
if (username !== 'admin' || password !== 'secret') {
reply.code(401);
return { error: 'Invalid credentials' };
}
const token = app.jwt.sign(
{ userId: 1, role: 'admin', username },
{ expiresIn: '1h' }
);
return { token, user: { id: 1, username, role: 'admin' } };
});
// Protected route
app.get('/me', { preHandler: [app.auth] }, async (request) => {
return { user: request.user };
});
await app.listen({ port: 3000 });
console.log('Auth server running');
}
build();