import cors from 'cors'; // Get allowed origins from environment variable or default to localhost const getOrigins = (): string[] => { const corsOrigin = process.env.CORS_ORIGIN; if (!corsOrigin) { return ['http://localhost:3000']; } // Handle both comma-separated string and single origin if (corsOrigin.includes(',')) { return corsOrigin.split(',').map(origin => origin.trim()); } return [corsOrigin.trim()]; }; export const corsMiddleware = cors({ origin: (origin, callback) => { const allowedOrigins = getOrigins(); // Allow requests with no origin (like mobile apps or curl requests) in development if (!origin && process.env.NODE_ENV === 'development') { return callback(null, true); } if (origin && allowedOrigins.includes(origin)) { callback(null, true); } else if (!origin) { // Allow requests with no origin callback(null, true); } else { callback(new Error('Not allowed by CORS')); } }, credentials: true, methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'], allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept'], exposedHeaders: ['X-Total-Count', 'X-Page-Count'], optionsSuccessStatus: 200, // Some legacy browsers (IE11, various SmartTVs) choke on 204 });