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

# Secure ActionHero APIs with API Key Authentication

Secure your ActionHero API using a shared secret.

## How Zuplo Handles It

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

## ActionHero Backend Code

```typescript
import { Middleware, api, env } from "actionhero";
import { timingSafeEqual } from "crypto";

export class SharedSecretMiddleware extends Middleware {
  constructor() {
    super();
    this.name = "sharedSecretMiddleware";
    this.global = false;
    this.priority = 1000;
  }

  async preProcessor(data) {
    const secret = data.connection.rawConnection.req.headers["x-shared-secret"];
    const expectedSecret = env.sharedSecret;

    if (!expectedSecret) {
      throw new Error("Server configuration error");
    }

    if (!secret) {
      throw new Error("No secret provided");
    }

    const secretBuffer = Buffer.from(secret);
    const expectedSecretBuffer = Buffer.from(expectedSecret);

    if (
      secretBuffer.length !== expectedSecretBuffer.length ||
      !timingSafeEqual(secretBuffer, expectedSecretBuffer)
    ) {
      throw new Error("Invalid secret");
    }
  }
}

api.actions.addMiddleware(new SharedSecretMiddleware());

// Define your Action

export class ProtectedAction extends api.Action {
  constructor() {
    super();
    this.name = "protectedAction";
    this.description = "An action that is protected by a shared secret";
    this.outputExample = { message: "Access granted" };
    // Register the middleware
    this.middleware = ["sharedSecretMiddleware"];
  }

  async run(data) {
    data.response.message = "Access granted";
  }
}

// Make sure to set your environment variable
// process.env.SHARED_SECRET = 'your-secret-value';
```

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