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

# Secure Restify APIs with API Key Authentication

Secure your Restify API using a shared secret.

## How Zuplo Handles It

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

## Restify Backend Code

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

// Middleware to validate shared secret header
function validateSharedSecret(req, res, next) {
  const secret = req.header("x-shared-secret");
  const expectedSecret = process.env.SHARED_SECRET;

  if (!expectedSecret) {
    res.send(500, { error: "Server configuration error" });
    return next(false);
  }

  if (!secret) {
    res.send(401, { error: "No secret provided" });
    return next(false);
  }

  // Use timing-safe comparison to prevent timing attacks
  if (
    secret.length !== expectedSecret.length ||
    !crypto.timingSafeEqual(Buffer.from(secret), Buffer.from(expectedSecret))
  ) {
    res.send(401, { error: "Invalid secret" });
    return next(false);
  }

  return next();
}

// Create server
const server = restify.createServer();

// Use the middleware for specific route
server.get("/protected", validateSharedSecret, (req, res, next) => {
  res.send({ message: "Access granted" });
  return next();
});

// Start server
server.listen(8080, () => {
  console.log("%s listening at %s", server.name, server.url);
});
```

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