CORS & Cookie Security
What CORS actually does, common misconfigurations that break security, and cookie security patterns for SPAs
Skills taught: websecurity.cors, websecurity.cors-misconfiguration, websecurity.preflight, websecurity.credentials-cors
CORS — relaxing the Same-Origin Policy
The Same-Origin Policy blocks JavaScript from reading cross-origin responses. CORS (Cross-Origin Resource Sharing) is the mechanism that lets a server say 'it's OK for other origins to read my responses'. Servers opt into it via response headers. CORS is not a security feature — it's a way to selectively relax a security feature (SOP). A misconfigured CORS policy can undo the protection SOP provides.
SIMPLE REQUESTS (GET, POST with safe content types):
1. Browser sends request with 'Origin: https://myapp.com' header
2. Server responds with 'Access-Control-Allow-Origin: https://myapp.com'
3. Browser checks: does origin match? Yes → JavaScript can read the response
PREFLIGHT (OPTIONS) — for non-simple requests:
1. Browser first sends: OPTIONS /api/users with:
Origin: https://myapp.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: Authorization, Content-Type
2. Server responds:
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, DELETE
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 86400 (cache preflight for 24 hours)
3. If approved: browser sends the actual DELETE request
KEY POINT:
CORS is enforced by the browser, not the server.
curl, Postman, and direct server-to-server calls bypass CORS entirely.
CORS prevents one website from reading another's data in a browser context.
It does NOT prevent a server from being directly attacked.
Safe vs dangerous CORS configurations
import cors from 'cors'; // npm install cors
// DANGEROUS — wildcard origin with credentials
// The browser actually blocks credentials with wildcard origin
// (Access-Control-Allow-Credentials: true + Access-Control-Allow-Origin: * is invalid)
// But this misconfiguration pattern is extremely common and confusing:
app.use(cors({ origin: '*' })); // Fine for public APIs, bad for credentialed ones
// DANGEROUS — reflecting the Origin header (trusts ANY origin)
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', req.headers.origin); // ← NEVER do this
res.header('Access-Control-Allow-Credentials', 'true');
next();
});
// This means ANY origin can read your API with user credentials
// A malicious site can read your users' private data
// SAFE — explicit allowlist of trusted origins
const ALLOWED_ORIGINS = [
'https://myapp.com',
'https://staging.myapp.com',
process.env.NODE_ENV === 'development' ? 'http://localhost:5173' : '',
].filter(Boolean);
app.use(cors({
origin: (origin, callback) => {
// Allow requests with no origin (mobile apps, curl, Postman)
if (!origin || ALLOWED_ORIGINS.includes(origin)) {
callback(null, true);
} else {
callback(new Error(`CORS: origin ${origin} not allowed`));
}
},
credentials: true, // Allow cookies to be sent cross-origin
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400, // Cache preflight response for 24 hours
}));
Cookie vs token auth for SPAs
OPTION 1: HttpOnly Cookie (recommended for web apps)
Storage: Browser sends automatically — not accessible to JS
CSRF risk: Yes — mitigated by SameSite=Lax
XSS risk: Low — JavaScript can't steal the cookie
CORS: Requires credentials: true + specific origin
Best for: Traditional web apps, first-party SPAs
OPTION 2: localStorage + Authorization header
Storage: Explicitly managed by JavaScript
CSRF risk: None — attacker can't read localStorage cross-site
XSS risk: HIGH — XSS can read localStorage and steal the token
CORS: Just needs Authorization header allowed
Best for: Mobile apps, non-browser clients, cross-origin SPAs
WARNING: If XSS exists, tokens are stolen and sessions persisted
OPTION 3: sessionStorage
Like localStorage but cleared when tab closes
Same XSS risk as localStorage
Slightly better (token dies with the tab)
OPTION 4: Memory (React state, not stored)
Most secure against XSS and CSRF
Lost on page refresh — need refresh token in httpOnly cookie to restore
Complex to implement
RECOMMENDATION FOR NEW APPS:
Use HttpOnly + SameSite=Lax cookie for the session
Use short-lived JWT (15 min) in memory + refresh token in httpOnly cookie
Never store long-lived tokens in localStorage
Frequently Asked Questions
My React app and API are on different domains. How do I set up cookies?
Set your session cookie with SameSite=None; Secure=true (required for cross-site cookies). Configure your API's CORS to specify the React app's exact origin and credentials: true. On the frontend, use fetch() or axios with credentials: 'include'. This is the standard pattern for SPAs on a different domain from their API. Without credentials: 'include', cookies are never sent with cross-origin requests.