Problem Statement
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls whether a web application running at one origin (like yourfrontend.com) can request resources from a different origin (like yourapi.com). You encounter this because when you build a modern web app with a separate frontend and backend, your JavaScript in the browser gets blocked from calling your own API. That infamous browser error—"Access to fetch at 'yourapi.com' from origin 'yourfrontend.com' has been blocked by CORS policy"—is CORS in action. It’s not a bug in your code; it’s the browser enforcing a critical security rule.
Core Explanation
Think of CORS as a nightclub bouncer for your API. By default, the browser acts as that bouncer, blocking any JavaScript request from a website to a different server. The only way in is if the requested server (the API) explicitly gives the browser a guest list.
This happens through a simple request-and-response check using special HTTP headers:
- The Request: Your browser sends a request from
yourfrontend.comtoyourapi.com. For "complex" requests (like those with JSON or custom headers), the browser first sends a preliminary preflight request using theOPTIONSmethod. - The Response: The server at
yourapi.commust include specific CORS headers in its response. The most critical isAccess-Control-Allow-Origin, which tells the browser which origin is allowed (e.g.,https://yourfrontend.comor*for any origin). - The Decision: The browser checks the server's headers. If the requesting origin (
yourfrontend.com) matches one allowed by the server'sAccess-Control-Allow-Originheader, the request proceeds. If not, the browser blocks the response and you see the error.
In short: CORS is a protocol where the server tells the browser which client origins are permitted to access its resources.
Practical Context
You need to configure CORS on your server when:
- You have a separate frontend (React, Angular, Vue app) and backend (Node.js, Python, .NET API) hosted on different domains or ports.
- You’re creating a public API intended to be consumed by web applications on other domains.
- You are developing locally with your frontend on
localhost:3000and your API onlocalhost:5000.
You do not need to worry about CORS when:
- Making requests from server-side code (Node.js, Python scripts, etc.), as CORS is a browser-only policy.
- Your frontend and backend are served from the exact same origin (same protocol, domain, and port). No cross-origin request is happening.
You should care because CORS is fundamental for building secure, modern web architectures. It prevents malicious websites from secretly making requests to other sites (like your bank) with your logged-in credentials. If you're doing any full-stack development, you will configure CORS on your server.
Quick Example
Here’s a minimal example of what your server must do. When a request comes in, the server needs to add the correct CORS headers to its response.
Node.js (Express) Snippet:
const express = require('express');
const app = express();
// Apply CORS middleware to all routes
app.use((req, res, next) => {
// Allow requests from this specific origin
res.header('Access-Control-Allow-Origin', 'https://myapp.com');
// Allow specific headers in requests (like 'Content-Type')
res.header('Access-Control-Allow-Headers', 'Content-Type');
// Allow specific HTTP methods
res.header('Access-Control-Allow-Methods', 'GET, POST');
next();
});
app.get('/api/data', (req, res) => {
res.json({ message: 'This is only for myapp.com!' });
});
This example shows the server's responsibility. It configures the Access-Control-Allow-Origin header to only allow requests from https://myapp.com. Without this header, a frontend hosted anywhere else cannot access the /api/data endpoint.
Key Takeaway
CORS errors are solved on the server, not the client. The next time you see a CORS error in the browser, your immediate action should be to check and correctly configure the CORS headers in your backend API. For a deep dive, the MDN Web Docs on CORS is the definitive resource.
Top comments (0)