Complete CORS Configuration Guide with Claude Code
A complete CORS configuration guide using Claude Code. Practical tips and code examples included.
Configure CORS Correctly With Claude Code
CORS (Cross-Origin Resource Sharing) is a mechanism that controls secure communication between different origins. Misconfiguration can lead to security risks or broken functionality. With Claude Code, you can accurately configure CORS to match your requirements.
CORS Basics
The Preflight Request Flow
> Explain how CORS preflight requests work.
> Include a sequence diagram.
For “non-simple requests,” the browser sends a preflight request using the OPTIONS method to confirm whether the server allows it. This includes things like requests with custom headers or JSON POST bodies.
Express.js Configuration
Per-Environment CORS
> Create a CORS config for Express.js.
> Requirements:
> - Allow only specific origins in production
> - Allow localhost in development
> - Support credentialed requests
> - Cache preflight responses
// src/middleware/cors.ts
import cors from 'cors';
const allowedOrigins: Record<string, string[]> = {
production: [
'https://myapp.example.com',
'https://admin.example.com',
],
development: [
'http://localhost:3000',
'http://localhost:5173',
],
};
export const corsMiddleware = cors({
origin: (origin, callback) => {
const env = process.env.NODE_ENV || 'development';
const origins = allowedOrigins[env] || allowedOrigins.development;
// Allow server-to-server calls (no origin)
if (!origin) return callback(null, true);
if (origins.includes(origin)) {
callback(null, true);
} else {
callback(new Error(`CORS: ${origin} is not allowed`));
}
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID'],
exposedHeaders: ['X-Total-Count', 'X-Request-ID'],
maxAge: 86400, // preflight cache: 24 hours
});
Configuration in Next.js
// next.config.js
const nextConfig = {
async headers() {
return [
{
source: '/api/:path*',
headers: [
{ key: 'Access-Control-Allow-Origin', value: 'https://myapp.example.com' },
{ key: 'Access-Control-Allow-Methods', value: 'GET,POST,PUT,DELETE' },
{ key: 'Access-Control-Allow-Headers', value: 'Content-Type,Authorization' },
{ key: 'Access-Control-Allow-Credentials', value: 'true' },
{ key: 'Access-Control-Max-Age', value: '86400' },
],
},
];
},
};
CORS Configuration in Nginx/CDN
> Add a CORS configuration to an Nginx reverse proxy.
location /api/ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' $http_origin;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE';
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Max-Age' 86400;
return 204;
}
add_header 'Access-Control-Allow-Origin' $http_origin always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
proxy_pass http://backend;
}
Troubleshooting
Common Errors and Solutions
Paste the browser console error into Claude Code and it will immediately tell you the cause and the fix.
Example error:
Access to XMLHttpRequest at 'https://api.example.com/data' from origin
'https://myapp.com' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested resource.
Common causes:
- CORS headers are not set on the server side
- Using
Access-Control-Allow-Origin: *together withcredentials: true(you must specify an explicit origin) - The server isn’t handling OPTIONS preflight requests
Security Considerations
Use Access-Control-Allow-Origin: * only for public APIs that don’t require authentication. For credentialed requests, always specify an explicit origin combined with credentials: true.
Summary
With Claude Code, you can accurately configure CORS for each environment and streamline troubleshooting. Also see the web security headers guide and the API development guide.
For more on CORS, see the MDN Web Docs - CORS.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 Deployment Checks Before You Publish a Multilingual Claude Code Article Every Day
A practical checklist for publishing daily multilingual Claude Code articles without missing locales, breaking CTAs, or shipping stale pages.
Codex Automations for Content Ops: A Daily Revenue Workflow for Claude Code Sites
Use Codex Automations to turn analytics, article updates, CTA improvements, deployment, and verification into a daily revenue workflow.
Claude Code × GCP Cloud Functions Complete Guide | Rapid Serverless Function Development
Streamline GCP Cloud Functions with Claude Code. Implement HTTP/Pub/Sub/Firestore triggers, local testing, and deployment automation with real-world code examples from Masa's experience.
Related Products
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.