typescriptbeginner
API Key Authentication Middleware
Simple API key validation middleware that checks the X-API-Key header against a set of valid keys.
typescriptPress ⌘/Ctrl + Shift + C to copy
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.
typescriptintermediate
JWT Verify Middleware
Express middleware that verifies JWT tokens from the Authorization header and attaches the decoded payload to the request.
Best for: REST API authentication
#jwt#express
typescriptintermediate
In-Memory Rate Limiter for Express
Token bucket rate limiter middleware for Express with configurable window and max requests per IP.
Best for: API abuse prevention
#express#rate-limit
typescriptadvanced
JWT Refresh Token Rotation
Implement secure token rotation with short-lived access tokens and one-time-use refresh tokens.
Best for: Secure API authentication
#jwt#authentication
typescriptbeginner
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
Best for: Express route error handling
#express#async