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

# Secure FoalTS APIs with API Key Authentication

Secure your FoalTS API using a shared secret.

## How Zuplo Handles It

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

## FoalTS Backend Code

```typescript
import {
  ctx,
  createController,
  dependency,
  Get,
  HttpResponseForbidden,
  HttpResponseInternalServerError,
  HttpResponseUnauthorized,
  Middleware,
  Post,
  ServiceManager,
} from "@foal/core";
import { hash, verify } from "@foal/password";
import { timingSafeEqual } from "crypto";

class SharedSecretMiddleware {
  async use(ctx: ctx, services: ServiceManager) {
    const secret = ctx.request.headers["x-shared-secret"];
    const expectedSecret = process.env.SHARED_SECRET;

    if (!expectedSecret) {
      return new HttpResponseInternalServerError({
        error: "Server configuration error",
      });
    }

    if (!secret) {
      return new HttpResponseUnauthorized({ error: "No secret provided" });
    }

    const isEqual =
      secret.length === expectedSecret.length &&
      timingSafeEqual(Buffer.from(secret), Buffer.from(expectedSecret));

    if (!isEqual) {
      return new HttpResponseForbidden({ error: "Invalid secret" });
    }
  }
}

class ApiController {
  @dependency
  sharedSecretMiddleware: SharedSecretMiddleware;

  @Get("/protected")
  @Middleware(SharedSecretMiddleware)
  async protected() {
    return { message: "Access granted" };
  }
}

export const apiController = createController(ApiController);
```

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