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.
Cross-Origin Resource Sharing
A security mechanism that controls access to resources from a different origin. Enforced by the browser. Permitted via server configuration.
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.
// 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' });
}
"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."
"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."
"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
Allowing all origins makes you vulnerable to CSRF attacks. In production, always specify the domains to allow.
If an OPTIONS call occurs on every request, performance degrades. Cache preflight responses with the Access-Control-Max-Age header.
Manage allowed origins with environment variables, and when using credentials, set explicit origins instead of a wildcard. Allow only the necessary methods and headers.