Use Cases

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 with credentials: 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.

#Claude Code #CORS #security #API #web development

Level up your Claude Code workflow

50 battle-tested prompt templates you can copy-paste into Claude Code right now.

Free

Free PDF: Claude Code Cheatsheet in 5 Minutes

Key commands, shortcuts, and prompt examples on a single printable page.

Download PDF
M

About the Author

Masa

Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.