Facebook Pixel

CORS: Real-World Examples

How CORS works in real applications with Express, Next.js, and more.

CORS: Real-World Examples

Express.js with cors middleware

const cors = require("cors"); app.use(cors({ origin: ["https://myapp.com", "https://admin.myapp.com"], methods: ["GET", "POST", "PUT", "DELETE"], credentials: true, }));

Next.js API Routes

export default function handler(req, res) { res.setHeader("Access-Control-Allow-Origin", "https://myapp.com"); res.setHeader("Access-Control-Allow-Methods", "GET, POST"); if (req.method === "OPTIONS") return res.status(204).end(); // handle request }

Vite Dev Proxy

// vite.config.js export default { server: { proxy: { "/api": { target: "https://api.example.com", changeOrigin: true } } } };

Nginx

location /api/ {
  add_header Access-Control-Allow-Origin "https://myapp.com";
  add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE";
  if ($request_method = OPTIONS) { return 204; }
  proxy_pass https://backend;
}

The Takeaway

Real-world CORS: Express (cors middleware), Next.js (set headers in API routes), Vite (dev proxy to avoid CORS in development), and Nginx (add_header for CORS). Always handle OPTIONS preflight with 204. Use a proxy in development to avoid CORS entirely.

Use the cors middleware: app.use(cors({ origin: ['https://myapp.com'], methods: ['GET', 'POST', 'PUT', 'DELETE'], credentials: true })). Or set headers manually and return 204 for OPTIONS.

Set headers in the handler: res.setHeader('Access-Control-Allow-Origin', 'https://myapp.com'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); if (req.method === 'OPTIONS') return res.status(204).end();

In vite.config.js: server: { proxy: { '/api': { target: 'https://api.example.com', changeOrigin: true } } }. Requests to /api are proxied to the API, avoiding CORS (same-origin from the browser's perspective).

add_header Access-Control-Allow-Origin 'https://myapp.com'; add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE'; if ($request_method = OPTIONS) { return 204; }. Add these to the location block for your API.

Use a proxy in development (simpler, avoids CORS entirely). Configure CORS on the server for production. The proxy makes the browser think the request is same-origin, so no CORS headers are needed.

Ready to master React completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.