# Authentication with JWT — Fastify

Source: https://www.geekswithgeeks.com/en/fastify/ff-authentication

> Implement token-based authentication in Fastify.

## JWT flow in Fastify

1) Client sends credentials to `/login`. 2) Server verifies and issues a JWT. 3) Client includes token in `Authorization: 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.

```javascript
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.

```javascript
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 };
});
```
