typescriptbeginner

API Key Authentication Middleware

Simple API key validation middleware that checks the X-API-Key header against a set of valid keys.

typescript
import { Request, Response, NextFunction } from 'express';

const VALID_KEYS = new Set(
  (process.env.API_KEYS || '').split(',').filter(Boolean)
);

export function apiKeyAuth(req: Request, res: Response, next: NextFunction) {
  const key = req.headers['x-api-key'] as string;
  if (!key || !VALID_KEYS.has(key)) {
    return res.status(401).json({ error: 'Invalid or missing API key' });
  }
  next();
}

Use Cases

  • Public API authentication
  • Third-party integrations

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.