Explain why CORS errors happen (Same-Origin Policy) and how to fix cross-origin requests safely: server-set Access-Control-Allow-Origin/Methods/Headers, correct preflight handling, or a backend proxy/BFF. The frontend alone cannot bypass CORS.
How would you securely handle CORS issues in a frontend application?
Key principle
CORS is part of the Same-Origin Policy enforced by the browser. If the API response doesn’t include the right CORS headers, the browser blocks your JavaScript from reading it. The fix is almost always server-side (or via a trusted proxy/BFF).
Frontend action | What it does (and doesn’t do) |
|---|---|
Use same-origin URLs (call your own domain) | Avoids CORS entirely if the API is served from the same origin. |
Remove custom headers / use simple requests | May avoid preflight, but still won’t bypass CORS if the server disallows the origin. |
Set | Sends cookies, but requires server to allow credentials and a specific origin. |
Use | Does not fix CORS; response becomes opaque and unusable. |
Header | Purpose |
|---|---|
| Allow only trusted origins (never use |
| Explicitly list allowed methods (GET, POST, etc.). |
| Allow only required headers (e.g., Authorization, Content-Type). |
| Needed for cookies; requires a specific origin (not |
| Cache preflight responses to reduce latency. |
| Prevents caches from mixing responses across origins. |
Preflight (OPTIONS) requests
Browsers send a preflight when a request is not “simple” (custom headers, non-GET/POST, or JSON content type). Your server must respond to OPTIONS with the same CORS headers or the real request will be blocked.
// Express example (server-side)
app.use((req, res, next) => {
const allowed = ['https://app.example.com'];
const origin = req.headers.origin || '';
if (allowed.includes(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Vary', 'Origin');
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
When you can’t change the API
Use a backend proxy/BFF: your frontend calls your own server, and your server calls the third-party API. This avoids CORS, keeps API keys private, and lets you enforce auth, logging, and rate limits.
Avoid these
- Disabling CORS in the browser or using extensions (not a real fix).
- Using
mode: 'no-cors'(opaque responses you cannot read). - Setting
Access-Control-Allow-Origin: *with credentials.
Interview-ready answer
You don’t “fix CORS” in the frontend; you configure the API (or a proxy/BFF) to allow trusted origins with the right CORS headers, handle preflight correctly, and avoid wildcard origins when credentials are involved.
Use the relevant interview-question hub first, then move into a concrete study plan before targeted company sets.