CORS Handling Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓CORS Handling runs in O(1) time and O(1) space, in JavaScript as in every other language.
- ✓node:http hands over the seam and no policy. req.headers is a plain object whose keys are already lowercased, res.setHeader and res.appendHeader mutate the outgoing map, and res.writeHead returns the response object so calls chain.
- ✓Reviewers want a Set and an exact has() check on the whole Origin string, never a String.includes or a hostname regex, since https://evil-app.example.dev contains app.example.dev.
- ✓The JavaScript trap: The client half fails silently, and this is the only language here that writes it. response.headers.get('X-Request-Id') returns null when the server omitted Access-Control-Expose-Headers: no console warning, no rejected promise, so the bug reads as a backend that stopped sending a header it is in fact still sending.
- ✓Headers here are ordinary V8 objects, so a request costs a few property reads plus one Set.has on an interned string, invisible next to HTTP parsing.
What CORS Handling actually is
CORS Handling in JavaScript: what you actually reach for
JavaScript implementation
import { createServer } from 'node:http';
const ALLOWED = new Set(['https://app.example.dev', 'https://ops.example.dev']);
const EXPOSED = 'X-Request-Id, X-Rate-Limit-Remaining';
function applyCors(req, res) {
// appendHeader, not setHeader: a compression layer may already vary on Accept-Encoding.
res.appendHeader('Vary', 'Origin');
const origin = req.headers.origin; // node lowercases every incoming header name
if (origin === undefined || !ALLOWED.has(origin)) return false;
res.setHeader('Access-Control-Allow-Origin', origin); // echo one origin, never '*'
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Expose-Headers', EXPOSED); // without this, fetch hides them
return true;
}
const server = createServer((req, res) => {
const allowed = applyCors(req, res);
const preflight = req.method === 'OPTIONS'
&& req.headers['access-control-request-method'] !== undefined;
if (preflight) {
res.appendHeader('Vary', 'Access-Control-Request-Headers');
if (allowed) {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers',
req.headers['access-control-request-headers'] ?? 'content-type');
res.setHeader('Access-Control-Max-Age', '600');
}
res.writeHead(204).end(); // writeHead returns the response, so this chains
return; // the router below never sees the probe
}
res.setHeader('X-Request-Id', 'req-91f3');
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ seats: 12 }));
});
server.listen(8080);Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for CORS Handling?
node:http hands over the seam and no policy. req.headers is a plain object whose keys are already lowercased, res.setHeader and res.appendHeader mutate the outgoing map, and res.writeHead returns the response object so calls chain. Express delegates to the third-party cors package, Fastify to @fastify/cors. On the browser side there is no API to call at all, because enforcement lives in the fetch machinery: fetch, XMLHttpRequest and EventSource apply the rules, and the Headers object of a cross-origin response is filtered down to the exposed list before your code sees it.
What is the most common JavaScript mistake when implementing CORS Handling?
The client half fails silently, and this is the only language here that writes it. response.headers.get('X-Request-Id') returns null when the server omitted Access-Control-Expose-Headers: no console warning, no rejected promise, so the bug reads as a backend that stopped sending a header it is in fact still sending. Worse, fetch(url, { mode: 'no-cors' }) resolves happily with an opaque Response whose status is 0, body is null and ok is false, so no catch block ever runs and the failure surfaces as a strange falsy check. Neither symptom reproduces under curl.
How does CORS Handling actually perform in JavaScript?
Headers here are ordinary V8 objects, so a request costs a few property reads plus one Set.has on an interned string, invisible next to HTTP parsing. The measurable effect is appendHeader on a name that already exists: Node promotes the stored value to an array and joins it at write time, so repeated appends in a middleware chain grow that array per request. Client side, omitting Access-Control-Max-Age turns every mutating call into two round trips, which on a 90ms link is the whole perceived latency of the feature. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.