Demystifying CORS, HTTP, and Security: A Builder’s Guide
A practical guide to the browser rules behind the red CORS error. You learn what an origin is, what the same-origin policy blocks, when the browser sends a preflight request, why credentials rule out the * wildcard, and how to set up an origin allowlist in Express. It also covers HTTPS and secure contexts, rate limiting, Content Security Policy and the server-side proxy pattern.

If you have built a frontend that talks to a separate backend, or called a third-party API from browser code, you have seen this error:
Access to fetch at 'https://api.domain.com' from origin 'https://my-app.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This guide is for developers who want to fix that error properly instead of hiding it. You'll learn what the browser checks, how to configure CORS on an Express server, and which other defences your API needs.
The tempting fixes are a browser extension that turns CORS off, or a wildcard header pasted into the server config. Both are mistakes. CORS isn't a bug. It's a controlled way to relax a browser rule that keeps one site from reading another site's data.
This is part 14 of the Frontend & JavaScript Fundamentals series. The previous part looked inside the V8 engine; this one moves out to the network.
Key takeaways
- The same-origin policy stops a page from reading responses from another origin. CORS headers from the server are how that server allows specific origins to read them.
- Requests with JSON bodies or an
Authorizationheader get a preflightOPTIONSrequest first. If the preflight fails, the real request is never sent. - CORS only protects users in browsers. It doesn't stop curl or scripts, so your API still needs authentication, HTTPS and rate limiting.
The backbone: HTTP
HTTP (HyperText Transfer Protocol) is how your browser, the client, talks to a server. MDN describes HTTP as stateless: the server keeps no link between two requests. You add context yourself, with a cookie or a bearer token. When you write an automation script, you build these HTTP messages directly.
The anatomy of a request
Every request has a method and a resource:
- GET: read data (
GET /api/users). - POST: create data or run an action (
POST /api/chat-completion). - PUT/PATCH: update data.
- DELETE: remove data.
The rest of the story is in the headers. Headers are metadata, like the envelope around a letter. They set content types, caching rules and, for this post, the security rules.
The rule: same-origin policy
To understand CORS, you need the same-origin policy first. MDN defines it as a browser security mechanism that restricts how a document or script from one origin can interact with a resource from another origin.
Two URLs have the same origin when all three of these match:
- Scheme (
httporhttps) - Host (
example.org,api.example.org) - Port (
:443,:3000)
So https://app.example.org and https://api.example.org are different origins, because the hosts differ.
If a page on https://my-dashboard.com calls fetch() on https://api.banking.com, the browser blocks your script from reading the response by default. It doesn't always block the request. MDN notes that cross-origin writes, such as form submissions, are typically allowed. A simple request often reaches the server and runs there. The browser just won't hand the result to your JavaScript.
Why? Without this rule, any site you visit could call your bank's API from your browser. If your browser attached your bank cookies, the site could read your account data.
Cookies have their own rules
Modern browsers also limit when cookies go to another site. MDN's Set-Cookie page explains the SameSite attribute: Strict sends the cookie only to the same site, Lax adds top-level navigations with safe methods such as GET, and None sends it everywhere but needs Secure. Some browsers use Lax when SameSite is missing. Mark session cookies HttpOnly too, so page scripts can't read them.
The exception: Cross-Origin Resource Sharing (CORS)
Frontends and APIs often live on different origins: a site on one host, an API on another, a dev server on localhost:3000.
CORS (Cross-Origin Resource Sharing) is an HTTP-header based mechanism that lets a server tell the browser which other origins may load its resources. It's an allowlist that the server sends and the browser enforces.
Simple requests and the preflight (OPTIONS)
This is where most developers get confused. You write one POST in your code, but the Network tab shows two requests: an OPTIONS request and then your POST.
The first one is the preflight. The Fetch standard and MDN set out when the browser can skip it. A "simple" request uses GET, HEAD or POST and only safelisted headers. Its Content-Type must be application/x-www-form-urlencoded, multipart/form-data or text/plain. Anything else needs a preflight. That includes a JSON body (application/json) and an Authorization header.
A preflight goes like this:
- The browser sends OPTIONS: "I'm a page from
https://my-app.com. I want to send aPOSTwith aContent-Typeheader. Is that allowed?" - The server answers: "Requests from
https://my-app.commay usePOSTand that header," usually with a204 No Contentstatus. - The browser sends the real POST.
If the server doesn't handle OPTIONS, or leaves out the right headers, the browser stops there. The real request is never sent. JavaScript only gets a generic network error, so check the browser console for the reason.
The server can let the browser reuse a preflight answer with Access-Control-Max-Age. MDN gives the default as 5 seconds, and each browser caps the value.
Credentials change the rules
By default, fetch() doesn't send cookies on cross-origin requests. You opt in with credentials: 'include'. MDN lists what the server must then do:
- Send
Access-Control-Allow-Credentials: true. - Name the exact origin in
Access-Control-Allow-Origin. The*wildcard isn't allowed with credentials. - Use explicit lists, not
*, for the allowed headers and methods too.
When the allowed origin changes per request, the server should also send Vary: Origin, so caches don't serve one origin's answer to another.
Implementing CORS safely in Express
If you're building an Express backend, the cors package handles these headers. Don't just install it and call it a day. Decide which origins you trust.
Two settings to understand before you ship
// Public, cookie-free data (a weather feed, a status page): fine
app.use(cors({ origin: '*' }));
// Dangerous: reflects ANY origin and allows cookies
app.use(cors({ origin: true, credentials: true }));
The first one lets any site read your responses to requests without credentials. If a request carries cookies, MDN says the browser blocks the page from reading a response marked *. So it suits public data with no login.
The second one is the real hole. origin: true copies whatever Origin the request sent back into Access-Control-Allow-Origin. With credentials: true on top, any website can call your API with the visitor's cookies and read the answer. In a test with cors@2.8.6, a request from https://evil.test got back Access-Control-Allow-Origin: https://evil.test and Access-Control-Allow-Credentials: true.
An origin allowlist
Here is a configuration that only trusts the origins you list:
import express from 'express';
import cors from 'cors';
const app = express();
// Comma-separated list of the exact origins your frontends run on
const allowedOrigins = (process.env.ALLOWED_ORIGINS ?? '')
.split(',')
.map((o) => o.trim())
.filter(Boolean);
const corsOptions = {
origin(origin, callback) {
// No Origin header: curl, server-to-server calls, same-origin GETs
if (!origin) return callback(null, true);
// false = no CORS headers, so the browser keeps the response from the page
callback(null, allowedOrigins.includes(origin));
},
methods: ['GET', 'POST', 'PUT'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-API-Key'],
credentials: true, // only if the frontend sends cookies
maxAge: 600, // let the browser reuse a preflight answer for 10 minutes
};
app.use(cors(corsOptions));
Checked against express@5.3.0 and cors@2.8.6 on Node.js 22, 2026-10-30. An allowed origin got its own origin back, Access-Control-Allow-Credentials: true and Vary: Origin. Its preflight returned 204 with the listed methods and headers. An unknown origin got no CORS headers at all.
The earlier version of this post rejected unknown origins with callback(new Error(...)). Express turns that into a 500 error for every bad origin. Passing false simply leaves the CORS headers out, which is all the browser needs to block the read.
The server still runs the request
In the same test, the POST from the unknown origin still reached the route and returned 200. CORS stops the page from reading the answer. It doesn't stop the server from doing the work. Protect state-changing routes with authentication and, for cookie sessions, SameSite cookies or CSRF tokens.
Beyond CORS: the rest of your API's defences
CORS only exists in the browser. If someone calls your API with Python or curl, CORS does nothing. It protects users' browsers, not your server. To secure an API, you need more.
1. HTTPS
Plain HTTP sends data as readable text. Anyone on the network path, such as a café's Wi-Fi or an ISP, can read an API key or password in it. HTTPS encrypts the connection with TLS.
Some browser features only work in a secure context. MDN's list includes the async Clipboard API, service workers and getUserMedia() for the camera and microphone. MDN also counts http://localhost as a secure context, so these work on your own machine without HTTPS. The trouble starts when you test from another device using a LAN IP address or a custom hostname. mkcert creates locally trusted certificates for that case.
2. Rate limiting
If you expose an LLM endpoint, you pay for every token, so one runaway client can run up a real bill. Add rate limiting on the server. With express-rate-limit:
import { rateLimit } from 'express-rate-limit';
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
limit: 100, // each IP gets 100 requests per window
standardHeaders: 'draft-8', // send RateLimit headers
legacyHeaders: false, // drop the old X-RateLimit-* headers
});
app.use('/api/', limiter);
Checked against express-rate-limit@8.7.2, 2026-10-30. The option used to be called max; the docs say it was renamed to limit in version 7, and max still works. The limiter counts per IP address by default. Behind a reverse proxy or load balancer, every request can appear to come from the proxy's IP, which turns the limiter into one global limit. The express-rate-limit docs fix this with app.set('trust proxy', 1), where the number is how many proxies sit between the user and your server. A per-user or per-API-key limit is often a better fit for paid endpoints.
3. Content Security Policy (CSP)
CORS decides which other sites may read your API's responses. Content Security Policy works on your own pages. It's a response header that tells the browser which scripts and other resources a page may load.
MDN describes CSP mainly as a defence against cross-site scripting (XSS). If someone injects a script into your comment section, a strict CSP can stop it from loading or running. MDN is clear that CSP doesn't replace input sanitizing. Use both, as defence in depth.
The proxy pattern
Sometimes you don't control the server. Your dashboard needs a third-party API that doesn't send CORS headers. You can't fix that from the frontend.
The answer is a proxy. Instead of Client -> Third-party API (blocked), you go Client -> Your server -> Third-party API.
CORS doesn't apply between servers. Your Next.js API route or Express server fetches the data and returns it to your frontend. If the frontend and the route share an origin, you need no CORS headers at all. This also keeps the third-party API key on your server, out of the browser.
Don't build an open proxy
Only forward to the hosts and paths you need, and require your own authentication. A proxy that fetches any URL a client sends lets anyone use your server to reach internal addresses (server-side request forgery) or to spend your API quota.
Summary
Web security isn't about memorizing acronyms. It's about knowing who sends what to whom.
- The same-origin policy is the default: pages can't read other origins' responses.
- CORS is the server's allowlist of origins that may read them.
- HTTPS protects the data on its way.
- Authentication, rate limits and CSP cover what CORS can't.
When the CORS error appears, don't hack around it. Configure the server for the exact origins you trust.
Next in the series, REST vs GraphQL compares two ways to design the APIs your frontend calls.
Frequently asked questions
Why does Postman or curl work when the browser shows a CORS error?
CORS is enforced by browsers, not servers. Postman and curl don't apply the same-origin policy, so they show the response whatever headers the server sends. The browser only lets your page read it when the server returns the right Access-Control-Allow-Origin header.
Why does my POST send an OPTIONS request first?
That's a preflight. The browser sends it when a request uses a method other than GET, HEAD or POST, a non-safelisted header such as Authorization, or a Content-Type such as application/json. Your server must answer the OPTIONS request with the matching CORS headers before the real request goes out.
Can I use Access-Control-Allow-Origin: * with cookies?
No. MDN states that for credentialed requests the server must name an explicit origin, not *. If it sends *, the browser blocks the response. Use an allowlist and send Vary: Origin as well.
Does CORS protect my API from attackers?
Not by itself. CORS controls which web pages can read responses in a browser. Anyone can call your API from a script, and the server still runs cross-origin requests it receives. Use authentication, HTTPS, rate limits and CSRF protection as well.
Is http://localhost a secure context?
Yes. MDN lists http://localhost as a secure context, so features such as the Clipboard API work there without HTTPS. A LAN IP address or a custom local hostname over plain HTTP is not secure, and that's where a tool like mkcert helps.
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
- MDN: Cross-Origin Resource Sharing (CORS)
- WHATWG Fetch Standard (CORS protocol, safelisted methods and headers)
- MDN: Same-origin policy
- MDN: Overview of HTTP
- MDN: Set-Cookie (SameSite, Secure, HttpOnly)
- MDN: Secure contexts
- MDN: Features restricted to secure contexts
- MDN: Content Security Policy (CSP)
- expressjs/cors README
- express-rate-limit: configuration
- express-rate-limit: troubleshooting proxy issues
- mkcert
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...