CORS and Cross-Origin Request Handling
🎯 Introduction
By the end of this article, you will be able to allow a specific frontend to read cross-origin API responses and configure preflight and cookie-bearing requests.
🌐 CORS determines whether a browser can read a response
A page at http://localhost:5173 and an API at http://127.0.0.1:3000 have different origins. The backend uses CORS response headers to tell the browser which origins may read responses.
Express projects use cors middleware to generate these headers and handle preflight. Install the dependency:
npm install cors@2.8.6
Create cors-server.mjs:
import express from 'express';
import cors from 'cors';
const app = express();
🏷 Configure the allowed frontend origin
Configure this before the routes:
app.use(cors({
origin: 'http://localhost:5173',
methods: ['GET', 'POST', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
origin is the page origin allowed to read responses and must include the actual scheme, host, and port. methods declares allowed request methods; allowedHeaders declares headers permitted by preflight.
This configuration returns the specified allowed origin. Browser pages from other origins cannot use it to read responses, but their requests may still reach the server. CORS does not replace authentication or CSRF protection.
📤 Add an endpoint and start the server
Continue with a test endpoint:
app.get('/profile', (req, res) => {
res.json({ name: 'Ming' });
});
app.listen(3000, '127.0.0.1');
Run node cors-server.mjs. A page at http://localhost:5173 requesting /profile can read {"name":"Ming"}. The allowed-methods list does not automatically create POST or PATCH endpoints.
📣 Middleware handles preflight
Cross-origin requests with Authorization or a JSON body may first send OPTIONS to ask whether the actual method and headers are allowed.
Inspect the preflight response:
curl -i -X OPTIONS http://127.0.0.1:3000/profile -H 'Origin: http://localhost:5173' -H 'Access-Control-Request-Method: PATCH' -H 'Access-Control-Request-Headers: content-type'
Expect 204 with the allowed origin, methods, and headers. Registered early in the app, cors handles these preflight requests without a separate set of routes.
curl does not enforce browser same-origin restrictions; it only inspects the response. Verify readability in a browser as well.
🍪 Configure both sides to send cookies
To include login cookies, replace the earlier cors configuration with:
app.use(cors({
origin: 'http://localhost:5173',
credentials: true,
methods: ['GET', 'POST', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
credentials: true adds the response header allowing credentials. The origin must then be explicit; * is not allowed.
The browser request must also enable credentials:
fetch('http://127.0.0.1:3000/profile', { credentials: 'include' });
Actual cookie transmission still depends on Domain, SameSite, Secure, and browser third-party cookie policies. Production configurations typically use HTTPS and explicit site relationships. CORS does not override cookie restrictions.
❓ Questions and Answers
Q1: Why does Postman work while the browser reports a cross-origin error?
Desktop API tools do not enforce browser read restrictions. Check that the actual page origin matches the CORS configuration.
Q2: Is configuring only the preflight response enough?
No. The actual response also needs permission headers. Registering cors before routes covers both stages.
Q3: Does disallowing an origin prevent it from modifying data?
You cannot assume that. The server must authenticate, authorize, and check CSRF protection before modifying data.
🧪 Practice
Change origin to another port and compare curl's ability to display the body with the browser page's inability to read it.
// Record your results here
