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

# Secure Express APIs with API Key Authentication

Secure your Express API using a shared secret.

## How Zuplo Handles It

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

## Express Backend Code

```javascript
const express = require("express");
const crypto = require("crypto");
require("dotenv").config();

const app = express();

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

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

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

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

  next();
}

// Example route protected by the middleware
app.get("/protected", validateSharedSecret, (req, res) => {
  res.json({
    message: "Access granted",
  });
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).json({ error: "Internal Server Error" });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
```

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