Q16: How do you handle Cross-Origin Resource Sharing (CORS) in Express?

Difficulty:EasyTopic:Security

CORS security headers prevent unauthorized browsers from making cross-origin requests to your backend API. CORS is typically enabled using the third-party cors middleware.

Configuring Restricted CORS Policies
const cors = require('cors');

const corsOptions = {
  origin: ['https://myapp.com', 'https://admin.myapp.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
};

app.use(cors(corsOptions));
💡 Restricting allowed origins prevents rogue client-side applications from making cross-origin requests.
Key Takeaways
  • Never use wildcard origin (*) in production applications handling sensitive credentials.
  • The cors middleware handles preflight OPTIONS requests automatically.