What Is CORS (Cross-Origin Resource Sharing)?

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls which websites can make requests to your server. By default, browsers block cross-origin requests (Same-Origin Policy). CORS headers let you selectively allow specific origins to access your API, while keeping everyone else blocked.

Types of CORS (Cross-Origin Resource Sharing)?

Simple Requests

GET, HEAD, or POST with standard headers — sent directly with an Origin header. The browser checks the response for Access-Control-Allow-Origin.

Preflight Requests

For non-simple requests (PUT, DELETE, custom headers), the browser sends an OPTIONS preflight first to check if the server allows the actual request.

Credentialed Requests

Requests with cookies or auth headers require Access-Control-Allow-Credentials: true and a specific origin (not wildcard *).

How to Prevent It

# Secure CORS configuration — Express.js
const allowedOrigins = ['https://myapp.com', 'https://admin.myapp.com'];

app.use((req, res, next) => {
  const origin = req.headers.origin;
  if (allowedOrigins.includes(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Access-Control-Allow-Credentials', 'true');
  }
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Access-Control-Max-Age', '86400');
  if (req.method === 'OPTIONS') return res.sendStatus(204);
  next();
});

# DANGEROUS — never do this in production:
# Access-Control-Allow-Origin: *
# Access-Control-Allow-Credentials: true
# (These two together are actually blocked by browsers)

Real-World Impact

Misconfigured CORS (especially reflecting any Origin with credentials) allows any website to make authenticated requests to your API, stealing user data, performing unauthorized actions, and exfiltrating sensitive information.

Related Questions

Scan your system prompt with LochBot — free, client-side, no data sent anywhere.

Frequently Asked Questions

What does CORS do?

CORS lets servers specify which other websites can make requests to them. Without CORS headers, browsers block cross-origin requests by default (Same-Origin Policy). CORS selectively relaxes this restriction for trusted origins.

Why do I get CORS errors?

CORS errors occur when your frontend (e.g., localhost:3000) makes a request to your backend (e.g., api.example.com) and the backend does not include the Access-Control-Allow-Origin header for your frontend's origin in its response.

Is Access-Control-Allow-Origin: * safe?

Wildcard (*) is safe for truly public APIs that serve non-sensitive data (public datasets, CDN assets). Never use * with Access-Control-Allow-Credentials: true — browsers block this combination. For APIs with authentication, whitelist specific origins.