QA
Beginner LevelExpress JS

What is CORS and how do you configure the cors middleware safely in Express?

❓ Interview Prompt: Explain Cross-Origin Resource Sharing (CORS), preflight OPTIONS requests, and why wildcard (*) origins are dangerous with authentication cookies.

CORS (Cross-Origin Resource Sharing) is a browser security mechanism blocking AJAX requests from a different domain than the server, unless explicitly permitted via HTTP headers.

Preflight ('OPTIONS') Requests:

For complex requests (PUT/DELETE or custom headers like 'Authorization'), the browser automatically sends an HTTP 'OPTIONS' preflight request to verify if the server permits the actual request.

Safe Express Configuration:

Use the official 'cors' npm package. *Never use 'origin: ""' in production* with authenticated sessions! Browsers reject responses using wildcard '' when requests include cookies ('credentials: "include"'). Whitelist explicit domains and set 'credentials: true'.

Code Implementation Example

javascript
import express from 'express';
import cors from 'cors';

const app = express();

const allowedOrigins = ['https://myadmin.com', 'https://www.myapp.com'];

const corsOptions = {
  origin: (origin, callback) => {
    if (!origin || allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error('Blocked by CORS policy'));
    }
  },
  credentials: true, // Required for cookies and Authorization headers!
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 86400 // Cache preflight OPTIONS response for 24 hours
};

app.use(cors(corsOptions));
💡Secure CORS middleware configuration with origin whitelisting and credentials.
🎯 Interview Key Takeaway

Never use wildcard (*) CORS origins with authenticated endpoints. Whitelist trusted frontend origins and enable credentials: true.

#CORS#Security#Headers#Beginner
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?