Practical CORS Configuration Security Guide for APIs
Secure cross-origin browser requests with explicit origin allowlists, correct preflight handling, and credential rules.
TechSilo
Technology writer & developer
Cross-Origin Resource Sharing (CORS) tells browsers which origins may read a server's responses from a different origin. It is a browser security mechanism—not a substitute for authentication, authorization, or CSRF defenses.
Start with the origin, not the URL path
An origin consists of a scheme, hostname, and port. These are different origins:
https://app.example.com
https://api.example.com
http://app.example.com
https://app.example.com:8443If a frontend hosted at https://app.example.com calls https://api.example.com, the API may need to opt in to that frontend's origin.
Express configuration with an allowlist
Install the middleware:
npm install express corsimport express from 'express';
import cors from 'cors';
const app = express();
const allowedOrigins = new Set([
'https://app.example.com',
'https://admin.example.com',
]);
app.use(cors({
origin(origin, callback) {
// No Origin header usually means a non-browser or same-origin request.
// It does not prove the request is trusted.
callback(null, Boolean(origin && allowedOrigins.has(origin)));
},
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
}));
app.get('/api/profile', (req, res) => res.json({ ok: true }));
app.listen(3000);A disallowed browser origin receives no matching Access-Control-Allow-Origin header, so the browser blocks JavaScript from reading the response. The server may still execute the request. Protect sensitive endpoints independently.
Preflight requests
For some cross-origin requests, browsers send an OPTIONS preflight first:
OPTIONS /api/profile HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorizationThe response must permit the origin, method, and requested headers. The cors middleware can handle standard preflight requests when installed for the route; ensure a proxy or API gateway does not block OPTIONS.
Cookies and credentials
When an application sends cross-origin credentials, a wildcard origin * is not accepted for credentialed browser reads. Return a specific allowed origin and Access-Control-Allow-Credentials: true, and configure browser requests appropriately.
For cross-site cookies, modern browsers enforce cookie rules such as SameSite=None; Secure where applicable. Third-party cookie restrictions may still prevent a session cookie from being sent. Do not loosen cookie security merely to silence a CORS error.
Security checklist
- Allow only controlled HTTPS origins in production.
- Avoid mirroring arbitrary Origin values.
- Require authorization on private API routes.
- Validate inputs even when the origin is allowed.
- Apply CSRF protection to state-changing cookie-authenticated requests.
- Consider Vary: Origin when responses vary by origin and pass through shared caches.
Test the actual response
curl -i -H "Origin: https://app.example.com" http://localhost:3000/api/profile
curl -i -H "Origin: https://untrusted.example" http://localhost:3000/api/profileCheck whether the first response allows your frontend and the second lacks an allowed origin. Remember that curl itself does not enforce browser CORS restrictions.
For a systematic debugging workflow, see [Troubleshooting CORS Errors in Production](/blog/troubleshooting-cors-errors-in-production-a-step-by-step-gui-msif3bmr).
Want to put this into practice?
Explore TechSilo's free developer tools for practical utilities you can use directly in your browser.
Related blog posts
Environment Variable Management: Secure Secrets and Deployment Practices
Keep environment configuration safe across local development, CI, and production without leaking API keys into browser bundles or logs.
Read postnpm Scripts Cheat Sheet: Commands, Arguments, and Automation
A developer reference for package.json scripts, npm run, pre/post hooks, environment variables, and safe task automation.
Read postAPI Authentication Patterns: Sessions, Tokens, and Service Credentials
Compare session cookies, bearer tokens, OAuth, and API keys, with practical protections against token leakage and authorization mistakes.
Read postPractical XSS Protection in React: Escaping, Sanitization, and CSP
Prevent cross-site scripting in React by understanding text escaping, dangerous HTML injection, safe URL handling, and Content Security Policy.
Read postPreventing SQL Injection: Parameterized Queries and Safe Database Access
Learn how SQL injection works and how to prevent it using parameterized queries, least-privilege database accounts, and input validation.
Read post