---
title: "Secure Fastify APIs with API Key Authentication"
description: "Secure your Fastify API using a shared secret."
canonicalUrl: "https://zuplo.com/use-cases/api-key-auth/javascript/fastify/secure-header"
framework: "Fastify"
language: "JavaScript"
authStrategy: "shared secret header"
pageType: use-case
---

# Secure Fastify APIs with API Key Authentication

Secure your Fastify API using a shared secret.

## How Zuplo Handles It

Put Zuplo in front of your Fastify backend to authenticate API keys and forward a shared secret header so your origin only accepts traffic from Zuplo.

## Fastify Backend Code

```javascript
const fastify = require("fastify")();
const crypto = require("crypto");

// Shared secret validation plugin
function validateSharedSecret(request, reply, done) {
  const secret = request.headers["x-shared-secret"];
  const expectedSecret = process.env.SHARED_SECRET;

  if (!expectedSecret) {
    reply.status(500).send({ error: "Server configuration error" });
    return;
  }

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

  // Use timing-safe comparison to prevent timing attacks
  const secretBuffer = Buffer.from(secret);
  const expectedBuffer = Buffer.from(expectedSecret);

  if (
    secretBuffer.length !== expectedBuffer.length ||
    !crypto.timingSafeEqual(secretBuffer, expectedBuffer)
  ) {
    reply.status(401).send({ error: "Invalid secret" });
    return;
  }

  done();
}

// Register the route with middleware
fastify.route({
  method: "GET",
  url: "/protected",
  preHandler: validateSharedSecret,
  handler: (request, reply) => {
    reply.send({ message: "Access granted" });
  },
});

// Start the server
fastify.listen(3000, (err, address) => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
  console.log(`Server running at ${address}`);
});
```

## 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)
