🌐 Web Development

CORS

Cross-Origin Resource Sharing

A security mechanism that controls access to resources from a different origin. Enforced by the browser. Permitted via server configuration.

πŸ“– Detailed Explanation

CORS (Cross-Origin Resource Sharing) is a security mechanism applied when a web browser accesses resources from a different origin (domain, protocol, port). By default, browsers follow the Same-Origin Policy and block access to resources from other origins, while CORS allows access only from origins that the server has explicitly permitted.

The background of CORS is web security. Without restrictions, a malicious site could call a user's banking site API and steal sensitive information. With CORS, the server specifies permitted origins using the Access-Control-Allow-Origin header, and the browser checks this and blocks requests that are not allowed.

CORS has two types of requests. A Simple Request is sent directly with GET or POST (with specific Content-Types), while a Preflight Request first checks whether the request is allowed using the OPTIONS method when PUT, DELETE, or custom headers are involved.

In practice, CORS errors are one of the errors frontend developers encounter most often. They occur during local development because localhost and the API server have different origins, and are resolved by setting appropriate CORS headers on the backend or worked around through a proxy.

πŸ’» Code Example

// Express.js CORS μ„€μ •
const express = require('express');
const cors = require('cors');
const app = express();

// λͺ¨λ“  좜처 ν—ˆμš© (개발용, ν”„λ‘œλ•μ…˜μ—μ„œ λΉ„κΆŒμž₯)
app.use(cors());

// νŠΉμ • 좜처만 ν—ˆμš© (ꢌμž₯)
app.use(cors({
  origin: ['https://myapp.com', 'https://admin.myapp.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,  // μΏ ν‚€ ν—ˆμš©
  maxAge: 86400,      // ν”„λ¦¬ν”ŒλΌμ΄νŠΈ μΊμ‹œ 24μ‹œκ°„
}));

// λΌμš°νŠΈλ³„ CORS μ„€μ •
app.get('/public', cors(), (req, res) => {
  res.json({ message: 'λˆ„κ΅¬λ‚˜ μ ‘κ·Ό κ°€λŠ₯' });
});

app.get('/private', cors({ origin: 'https://admin.myapp.com' }), (req, res) => {
  res.json({ message: 'κ΄€λ¦¬μžλ§Œ μ ‘κ·Ό κ°€λŠ₯' });
});

// Next.js API Routeμ—μ„œ CORS μ„€μ •
// pages/api/data.ts
export default function handler(req, res) {
  res.setHeader('Access-Control-Allow-Origin', 'https://myapp.com');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

  if (req.method === 'OPTIONS') {
    return res.status(200).end();  // ν”„λ¦¬ν”ŒλΌμ΄νŠΈ 응닡
  }

  res.json({ data: 'Hello' });
}

πŸ—£οΈ Say It Like This in Practice

πŸ’¬ In a Meeting
"I'm getting a CORS error when calling the API locally. Could you add localhost:3000 to the allowlist on the backend, or I'll set up a proxy with Next.js rewrites. In production, we only need to allow the actual domain."
πŸ’¬ In an Interview
"CORS is a browser security policy. The server specifies allowed origins with the Access-Control-Allow-Origin header, and the browser verifies it. For requests like PUT or DELETE, a preflight OPTIONS request is sent first to check whether the request is allowed."
πŸ’¬ In a code review
"Setting Access-Control-Allow-Origin: * is risky in production. Specify the domains to allow, and when credentials: true is used, a wildcard is not allowed at all. Separate the settings by environment."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Common Mistakes & Cautions

❌
Overuse of the wildcard (*)

Allowing all origins makes you vulnerable to CSRF attacks. In production, always specify the domains to allow.

❌
Ignoring preflight caching

If an OPTIONS call occurs on every request, performance degrades. Cache preflight responses with the Access-Control-Max-Age header.

βœ…
The right pattern

Manage allowed origins with environment variables, and when using credentials, set explicit origins instead of a wildcard. Allow only the necessary methods and headers.

πŸ”— Related Terms

πŸ“š Learn More