Skip to content

CORS

CORS

Medium — good to knowSecurity

ELI5 — The Vibe Check

CORS (Cross-Origin Resource Sharing) is the browser's built-in protection that prevents random websites from making API calls to your backend using the visitor's cookies. Your browser blocks cross-origin requests unless your server explicitly says 'yes, that website is allowed'. It stops sneaky sites from piggybacking on your logged-in sessions.

Real Talk

CORS is a browser security mechanism that restricts cross-origin HTTP requests. When a browser makes a cross-origin request, it checks for CORS headers (Access-Control-Allow-Origin, etc.) in the server response. Preflight OPTIONS requests verify permissions before sending actual requests.

Show Me The Code

// Express: configure CORS properly
import cors from 'cors';

app.use(cors({
  origin: ['https://myapp.com', 'https://www.myapp.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true, // allow cookies
}));

// ❌ Never do this in production:
// app.use(cors({ origin: '*', credentials: true })); // breaks & insecure

When You'll Hear This

"The frontend is getting a CORS error — whitelist the domain in the API." / "Don't set Access-Control-Allow-Origin: * on authenticated endpoints."

Made with passive-aggressive love by manoga.digital. Powered by Claude.