CORS (Cross-Origin Resource Sharing) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain of the web page. It's essential for enabling secure communication between frontend and backend services across different origins.

How CORS Works 🔍

  1. Browser Request
    When a frontend makes a request to a different origin, the browser automatically includes an Origin header.
  2. Server Response
    The backend must respond with appropriate CORS headers like:
    • Access-Control-Allow-Origin (specifies allowed origins)
    • Access-Control-Allow-Methods (lists allowed HTTP methods)
    • Access-Control-Allow-Headers (defines allowed request headers)
  3. Pre-flight Requests
    For non-simple requests (e.g., PUT, DELETE), browsers send an OPTIONS pre-flight check.

CORS Configuration 🔧

  • Node.js (Express)
    app.use((req, res, next) => {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    
  • Nginx
    Add to server block:
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
    
  • Apache
    Use .htaccess:
    Header set Access-Control-Allow-Origin "*"
    

Common Issues ⚠️

  • 403 Forbidden
    Indicates missing Access-Control-Allow-Origin header.
  • Preflight Failure
    Check if OPTIONS request is properly handled.
  • Header Mismatch
    Ensure Access-Control-Allow-Headers matches client request headers.

For deeper insights into implementing CORS in your project, check out our Cross-Origin Resource Sharing Configuration guide.

CORS Overview
CORS Configuration
CORS Example