Dev

CORS Explained - The #1 Reason Your API Returns 403

Mohssine kissane
CORS Explained - The  #1  Reason Your API Returns 403

Mohssine kissane

Software engineer

90% of developers encounter CORS errors in their first week. Here's what's actually happening .

What : CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts HTTP requests between different origins (domain, protocol, or port). An origin is the combination of protocol + domain + port.

Why: Browsers implement the Same-Origin Policy to prevent malicious websites from accessing sensitive data. CORS provides a controlled way to relax this restriction by allowing servers to specify which origins can access their resources.


How:

cors
// Express.js
const cors = require('cors');

// Allow specific origin
app.use(cors({
  origin: 'https://yourapp.com',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  credentials: true
}));

// Manual configuration
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'https://yourapp.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

Critical points:

  • CORS is configured server-side, not client-side
  • Preflight requests (OPTIONS) check permissions before actual requests
  • Access-Control-Allow-Origin: * works for public APIs only
  • Always specify exact origins in production for security