---
title: "Add JWT Authentication to Your Fastify API"
description: "Secure your Fastify API using JWT authentication with JWKS."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/javascript/fastify/jwt-backend"
framework: "Fastify"
language: "JavaScript"
authStrategy: "JWT with JWKS"
pageType: use-case
---

# Add JWT Authentication to Your Fastify API

Secure your Fastify API using JWT authentication with JWKS.

## How Zuplo Handles It

Let Zuplo issue short-lived JWTs signed with a JWKS your Fastify backend can verify — no long-lived API keys touch your origin.

## Fastify Backend Code

```javascript
const fastify = require("fastify")();
const jwt = require("jsonwebtoken");
const jwksClient = require("jwks-rsa");

const ISSUER = "https://my-api-a32f34.zuplo.api/__zuplo/issuer";

const client = jwksClient({
  jwksUri: `${ISSUER}/.well-known/jwks.json`,
  cache: true,
  cacheMaxAge: 600000,
});

function getKey(header, callback) {
  client.getSigningKey(header.kid, (err, key) => {
    if (err) {
      return callback(err);
    }
    const signingKey = key.getPublicKey();
    callback(null, signingKey);
  });
}

async function validateJwt(request, reply) {
  const token = request.headers.authorization?.replace("Bearer ", "");

  if (!token) {
    reply.code(401).send({ error: "No token provided" });
    return;
  }

  try {
    const decoded = await new Promise((resolve, reject) => {
      jwt.verify(
        token,
        getKey,
        { issuer: ISSUER, algorithms: ["RS256"] },
        (err, decoded) => {
          if (err) reject(err);
          else resolve(decoded);
        },
      );
    });
    request.user = decoded;
  } catch (err) {
    reply.code(401).send({ error: "Invalid token", details: err.message });
  }
}

fastify.addHook("preHandler", validateJwt);

fastify.get("/protected", async (request, reply) => {
  return { message: "Access granted", user: request.user };
});

fastify.listen({ port: 3000 }, (err) => {
  if (err) throw err;
  console.log("Server running on port 3000");
});
```

## Example Request

```bash
curl -X GET \
  'https://your-api.zuplo.dev/your-route' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

## Learn More

- [API Key Authentication on Zuplo](https://zuplo.com/docs/policies/api-key-auth-inbound)
- [JWT Authentication on Zuplo](https://zuplo.com/docs/policies/open-id-jwt-auth-inbound)
- [All use cases](https://zuplo.com/use-cases)
