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

# Secure Total.js APIs with API Key Authentication

Secure your Total.js API using a shared secret.

## How Zuplo Handles It

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

## Total.js Backend Code

```javascript
// Install Total.js from npm: npm install total.js

const crypto = require("crypto");

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

  if (!expectedSecret) {
    return res.throw500("Server configuration error");
  }

  if (!secret) {
    return res.throw401("No secret provided");
  }

  // 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)
  ) {
    return res.throw401("Invalid secret");
  }

  next();
}

// Total.js application setup
const framework = require("total.js");
const app = framework.http("release");

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

app.listen(8000, () => framework.console.log("Server running on port 8000"));
```

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