Skip to main content

🌐 What is CORS?

πŸ“– Definition​

CORS (Cross-Origin Resource Sharing) is a security mechanism that tells browsers to allow access to resources from different origins. Browsers restrict cross-origin resource requests by default for security reasons, and CORS is the method to safely permit this.

🎯 Understanding with Analogy​

Apartment Security System​

Imagine you live in Building A:

  • Same-Origin: Call from A-101 to A office β†’ Freely allowed βœ…
  • Cross-Origin: Call from A-101 to B office β†’ Security check required πŸ”’
  • CORS Setting: Building B says "I'll accept calls from Building A" β†’ Call allowed βœ…

βš™οΈ How It Works​

1. What is Origin?​

Origin is the combination of protocol, domain, and port:

https://www.example.com:443/page
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ └─ Port (443 if omitted)
β”‚ β”‚ └───────────── Domain
β”‚ └───────────────── Protocol
└──────────────────────── Origin

2. Same-Origin vs Cross-Origin​

// Current page: https://www.example.com

βœ… Same-Origin
- https://www.example.com/page
- https://www.example.com/api/users

❌ Cross-Origin
- http://www.example.com // Different protocol
- https://api.example.com // Different domain
- https://www.example.com:8080 // Different port

3. CORS Request Process​

Simple Request​

1. Browser β†’ Server: Send request
GET https://api.example.com/data
Origin: https://www.mysite.com

2. Server β†’ Browser: Response
Access-Control-Allow-Origin: https://www.mysite.com

3. Browser: Check response
- If allowed origin β†’ Deliver data βœ…
- If not allowed β†’ CORS error ❌

Preflight Request​

1. Browser β†’ Server: Pre-check (OPTIONS)
OPTIONS https://api.example.com/data
Origin: https://www.mysite.com

2. Server β†’ Browser: Permission response
Access-Control-Allow-Origin: https://www.mysite.com
Access-Control-Allow-Methods: POST, GET

3. Browser β†’ Server: Actual request (POST)
4. Server β†’ Browser: Data response

πŸ’‘ Real Examples​

Enabling CORS on Server​

Express.js (Node.js)​

const express = require('express');
const cors = require('cors');
const app = express();

// Method 1: Allow all origins (development)
app.use(cors());

// Method 2: Allow specific origin (production recommended)
app.use(cors({
origin: 'https://www.mysite.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true,
maxAge: 3600
}));

// Method 3: Allow multiple origins
const allowedOrigins = [
'https://www.mysite.com',
'https://admin.mysite.com'
];

app.use(cors({
origin: function(origin, callback) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
}));

πŸ€” FAQ​

Q1. Why is CORS needed?

A: For security. Without CORS:

// Malicious site (evil.com)
fetch('https://bank.com/api/transfer', {
method: 'POST',
credentials: 'include', // Includes user's bank cookies
body: JSON.stringify({
to: 'hacker-account',
amount: 1000000
})
});

// CORS blocks such attacks!

Q2. How to solve CORS errors?

A: Depending on the situation:

// 1. If you control the server β†’ Add CORS headers (recommended)
app.use(cors({ origin: 'https://frontend.com' }));

// 2. If you don't control server β†’ Use proxy server
// package.json (Create React App)
{
"proxy": "https://api.example.com"
}

// 3. Development environment β†’ Proxy middleware
// setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
app.use('/api', createProxyMiddleware({
target: 'https://api.example.com',
changeOrigin: true
}));
};

Q3. When to use credentials: 'include'?

A: When sending cookies or authentication information:

// Frontend
fetch('https://api.example.com/profile', {
credentials: 'include' // Include cookies
});

// Backend - Must explicitly specify origin
app.use(cors({
origin: 'https://www.mysite.com', // Cannot use '*'!
credentials: true
}));

Q4. Difference between CORS and CSRF?

A: Completely different security concepts:

CORS (Cross-Origin Resource Sharing)
β”œβ”€ Purpose: Allow cross-origin resource access
β”œβ”€ Operation: Browser blocks/allows responses
└─ Solution: Add allow headers on server

CSRF (Cross-Site Request Forgery)
β”œβ”€ Purpose: Prevent forged requests
β”œβ”€ Operation: Malicious site sends requests
└─ Solution: Use CSRF tokens

🎬 Summary​

CORS is a core web security concept:

  • Origin: Combination of protocol + domain + port
  • Same-Origin Policy: Blocks different origins by default
  • CORS: Safely allows different origins
  • Preflight: Pre-check for complex requests

When CORS errors occur, don't panic - resolve safely by setting appropriate headers on the server! 🌐✨