API Developmentbeginner
Configure CORS properly for different environments
CORS Configurator
Configure CORS properly for different environments
Configure CORS properly for different environments.
Instructions
// middleware.ts (Next.js)
const allowedOrigins = {
development: ['http://localhost:3000', 'http://localhost:5173'],
production: ['https://myapp.com', 'https://admin.myapp.com'],
};
export function middleware(request: NextRequest) {
const origin = request.headers.get('origin');
const env = process.env.NODE_ENV ?? 'development';
const origins = allowedOrigins[env] ?? [];
// Preflight
if (request.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: {
'Access-Control-Allow-Origin': origins.includes(origin!) ? origin! : '',
'Access-Control-Allow-Methods': 'GET, POST, PUT, PATCH, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Max-Age': '86400', // cache preflight for 24h
},
});
}
const response = NextResponse.next();
if (origins.includes(origin!)) {
response.headers.set('Access-Control-Allow-Origin', origin!);
response.headers.set('Access-Control-Allow-Credentials', 'true');
}
return response;
}
Rules
- Never use
Access-Control-Allow-Origin: *with credentials - Whitelist specific origins — never wildcard in production
- Cache preflight responses to reduce OPTIONS requests