Medium10 minWeb Fundamentals
UpdatedAug 2, 2026
Edit

What is CORS?

CONCEPTS:Cross-Origin Resource Sharing (CORS)

Question Variations

  • "What is CORS (Cross-Origin Resource Sharing), and why do browsers enforce it?"
  • "What is a 'preflight request,' and when does the browser trigger one?"
  • "How do you fix a CORS error in a frontend application?"
  • "Explain the difference between the 'Same-Origin Policy' and CORS."

Why This Is Asked

CORS is one of the most common hurdles web developers face. Interviewers want to know if you understand the underlying security model of the web and how to properly configure communication between a frontend and a backend hosted on different domains.

Key Concepts

  • Same-Origin Policy (SOP): The default browser security.
  • Preflight Requests: Why the browser sends an OPTIONS request.
  • Origin definition: Domain + Port + Protocol.
  • Security Implications: Why Access-Control-Allow-Origin: * is dangerous in some contexts.

Question Variations

  • “What is CORS (Cross-Origin Resource Sharing), and why do browsers enforce it?”
  • “What is a ‘preflight request,’ and when does the browser trigger one?”
  • “How do you fix a CORS error in a frontend application?”
  • “Explain the difference between the ‘Same-Origin Policy’ and CORS.”

Answers by Technology

+ Add Variant

Expected Answer

CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers. It allows servers to specify who can access their resources from a different origin. An origin is defined by the combination of the protocol (http vs https), the domain (example.com), and the port (80 vs 443).

If your frontend is at app.example.com and it tries to fetch data from api.example.com, the browser will block the request unless api.example.com sends back the header Access-Control-Allow-Origin: https://app.example.com.

For complex requests (like those with JSON bodies), the browser performs a Preflight—it sends an OPTIONS request first to ask the server for permission before sending the actual data.

Why It Matters

Without CORS (and the Same-Origin Policy), any website you visit could use your browser to make authenticated requests to another site where you are logged in (like your email or bank), potentially stealing your data. Understanding CORS is essential for debugging the “CORS error” in the console and for building secure APIs.

Example Scenario

1. The Preflight (OPTIONS)

Browser sends:

OPTIONS /data HTTP/1.1
Origin: https://my-app.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type

2. The Server Response

Server sends:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://my-app.com
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type

3. The Actual Request

If the server response matches, the browser finally sends the POST request.

Common Mistakes

  • Using * with credentials: You cannot use Access-Control-Allow-Origin: * if you also need to send cookies (Access-Control-Allow-Credentials: true). You must specify the exact origin.
  • Thinking CORS is a server-side protection: CORS is a browser protection. A tool like curl or a backend server can still call your API regardless of CORS settings.
  • Handling CORS only in the app logic: Forgetting that the web server (Nginx/Apache) or a Load Balancer might also need to be configured to handle the OPTIONS preflight.

Follow-up Questions

  • What is a “Simple Request”? (Answer: A request using GET, HEAD, or POST with standard content types like text/plain or application/x-www-form-urlencoded that doesn’t trigger a preflight).
  • How can you bypass CORS during development? (Answer: Using a proxy in your dev server, or a browser extension that disables CORS checks—though the latter is not recommended).
  • What is the difference between Access-Control-Allow-Origin and Access-Control-Expose-Headers? (Answer: The first allows the browser to receive the response; the second allows the frontend code to read specific custom headers from that response).

References

Expected Answer (Express 5.1.0 / Node.js 18+)

CORS is a browser protocol enforced through response headers. An Express API must explicitly opt in when a browser page from one origin should read its response from another origin. For simple requests, set a matching Access-Control-Allow-Origin response header. For non-simple requests, such as a JSON POST with an authorization header, browsers first send an OPTIONS preflight; the server must allow the intended origin, method, and request headers.

Configure CORS as an allow-list based on the actual client origins. If the API uses cookies or other credentials, set Access-Control-Allow-Credentials: true and return a specific allowed origin—not *. CORS is not authentication, authorization, CSRF protection, or a way to protect an API from non-browser callers. The server must enforce each of those separately.

Why It Matters

An overly broad policy can expose credentialed browser responses, while an incomplete preflight policy causes client failures that look unrelated to the API endpoint.

Code Example

import express, { NextFunction, Request, Response } from 'express';

const app = express();
const origin = 'https://app.example.com';
app.use((req: Request, res: Response, next: NextFunction) => {
  if (req.get('origin') === origin) {
    res.set('Access-Control-Allow-Origin', origin);
    res.set('Access-Control-Allow-Methods', 'GET,POST');
    res.set('Access-Control-Allow-Headers', 'Content-Type,Authorization');
  }
  if (req.method === 'OPTIONS') return res.sendStatus(204);
  return next();
});
app.get('/profile', (_req: Request, res: Response) => res.json({ name: 'Ada' }));
app.listen(3000);

Common Mistakes

  • Thinking CORS rejects malicious server-to-server requests: Non-browser clients do not enforce browser CORS rules.
  • Using wildcard origin with credentials: Browsers will not allow credentialed responses with Access-Control-Allow-Origin: *.

Follow-up Questions

  • What triggers a preflight request? (Answer: Non-simple methods, headers, or content types cause the browser to issue OPTIONS first.)
  • Should CORS replace CSRF controls for cookies? (Answer: No; CORS controls response reading, while CSRF defenses protect state-changing cookie-based requests.)

Expected Answer (Koa 3.2.1 / Node.js 18+)

CORS is enforced by browsers through HTTP response headers. A Koa API should allow only known origins, methods, and headers needed by its browser clients. Credentialed requests require an explicit allowed origin and credentials header; * cannot be used for that case. Preflight OPTIONS requests must be handled for non-simple browser requests.

CORS is not authentication or authorization. Non-browser callers do not enforce it, so protected Koa routes still need server-side identity and permission checks.

Why It Matters

Tight CORS settings prevent unintended browser access, while correct preflight support prevents legitimate clients from failing before the route executes.

Code Example

import Koa, { Context, Next } from 'koa';

const app = new Koa();
app.use(async (ctx: Context, next: Next) => {
  if (ctx.get('origin') === 'https://app.example.com') ctx.set('Access-Control-Allow-Origin', 'https://app.example.com');
  if (ctx.method === 'OPTIONS') { ctx.status = 204; return; }
  await next();
});
app.use((ctx: Context) => { ctx.body = { ok: true }; });
app.listen(3000);

Common Mistakes

  • Treating CORS as access control: It does not stop direct API calls.
  • Using wildcard origins for cookie requests: Browsers disallow that credentialed configuration.

Follow-up Questions

  • What triggers a preflight? (Answer: Non-simple methods, headers, or content types.)
  • Should CORS replace CSRF defenses? (Answer: No; they address different threats.)