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

# Secure undefined APIs with API Key Authentication



## How Zuplo Handles It

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

## undefined Backend Code

```typescript
import {
  Injectable,
  NestMiddleware,
  UnauthorizedException,
  InternalServerErrorException,
} from "@nestjs/common";
import { Request, Response, NextFunction } from "express";
import * as crypto from "crypto";

// Middleware to validate shared secret header
@Injectable()
export class ValidateSharedSecretMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    const secret = req.headers["x-shared-secret"] as string;
    const expectedSecret = process.env.SHARED_SECRET;

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

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

    // Use timing-safe comparison to prevent timing attacks
    if (
      secret.length !== expectedSecret.length ||
      !crypto.timingSafeEqual(Buffer.from(secret), Buffer.from(expectedSecret))
    ) {
      throw new UnauthorizedException("Invalid secret");
    }

    next();
  }
}

// Apply middleware to the desired route using a module
import { Module, MiddlewareConsumer, RequestMethod } from "@nestjs/common";
import { APP_CONTROLLER } from "./app.controller";

@Module({
  controllers: [APP_CONTROLLER],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(ValidateSharedSecretMiddleware)
      .forRoutes({ path: "protected", method: RequestMethod.GET });
  }
}

// Controller to handle the protected route
import { Controller, Get } from "@nestjs/common";

@Controller("protected")
export class APP_CONTROLLER {
  @Get()
  getProtectedResource() {
    return { message: "Access granted" };
  }
}
```

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