|
| 1 | +import { Injectable, NestMiddleware } from '@nestjs/common'; |
| 2 | +import { Request, Response, NextFunction } from 'express'; |
| 3 | + |
| 4 | +export interface CorsOptions { |
| 5 | + origins?: string | string[]; |
| 6 | + methods?: string[]; |
| 7 | + allowedHeaders?: string[]; |
| 8 | + exposedHeaders?: string[]; |
| 9 | + credentials?: boolean; |
| 10 | + maxAge?: number; |
| 11 | +} |
| 12 | + |
| 13 | +const DEFAULTS: Required<CorsOptions> = { |
| 14 | + origins: '*', |
| 15 | + methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], |
| 16 | + allowedHeaders: ['Content-Type', 'Authorization', 'X-Correlation-ID', 'X-Idempotency-Key'], |
| 17 | + exposedHeaders: ['X-Correlation-ID'], |
| 18 | + credentials: false, |
| 19 | + maxAge: 86400, |
| 20 | +}; |
| 21 | + |
| 22 | +@Injectable() |
| 23 | +export class CorsMiddleware implements NestMiddleware { |
| 24 | + private readonly opts: Required<CorsOptions>; |
| 25 | + |
| 26 | + constructor(options: CorsOptions = {}) { |
| 27 | + this.opts = { ...DEFAULTS, ...options }; |
| 28 | + } |
| 29 | + |
| 30 | + use(req: Request, res: Response, next: NextFunction): void { |
| 31 | + const { origins, methods, allowedHeaders, exposedHeaders, credentials, maxAge } = this.opts; |
| 32 | + const reqOrigin = req.headers.origin; |
| 33 | + |
| 34 | + if (Array.isArray(origins)) { |
| 35 | + if (reqOrigin && origins.includes(reqOrigin)) { |
| 36 | + res.setHeader('Access-Control-Allow-Origin', reqOrigin); |
| 37 | + res.setHeader('Vary', 'Origin'); |
| 38 | + } |
| 39 | + } else { |
| 40 | + res.setHeader('Access-Control-Allow-Origin', origins); |
| 41 | + } |
| 42 | + |
| 43 | + res.setHeader('Access-Control-Allow-Methods', methods.join(', ')); |
| 44 | + res.setHeader('Access-Control-Allow-Headers', allowedHeaders.join(', ')); |
| 45 | + |
| 46 | + if (exposedHeaders.length) { |
| 47 | + res.setHeader('Access-Control-Expose-Headers', exposedHeaders.join(', ')); |
| 48 | + } |
| 49 | + |
| 50 | + if (credentials) { |
| 51 | + res.setHeader('Access-Control-Allow-Credentials', 'true'); |
| 52 | + } |
| 53 | + |
| 54 | + if (req.method === 'OPTIONS') { |
| 55 | + res.setHeader('Access-Control-Max-Age', String(maxAge)); |
| 56 | + res.status(204).end(); |
| 57 | + return; |
| 58 | + } |
| 59 | + |
| 60 | + next(); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +/** Factory for use with NestJS consumer.apply() */ |
| 65 | +export function corsMiddleware(options?: CorsOptions) { |
| 66 | + const mw = new CorsMiddleware(options); |
| 67 | + return (req: Request, res: Response, next: NextFunction) => mw.use(req, res, next); |
| 68 | +} |
0 commit comments