Introduction
When a web application running on one origin (domain, protocol, or port) attempts to access resources from another origin, browsers enforce the Same-Origin Policy. To safely allow cross-origin requests, servers must include appropriate CORS (Cross-Origin Resource Sharing) headers in their responses.
Information
What is CORS?
CORS is a mechanism that allows a server to specify which origins, HTTP methods, and request headers are permitted to access its resources. Without the correct CORS headers, browsers block cross-origin requests even if the server responds successfully.
Understanding Origins
An origin is defined by the combination of protocol, hostname, and port. Two URLs belong to the same origin only if all three match.
| Current Origin | Requested Origin | Same Origin? |
|---|---|---|
| http://localhost:3000 | http://localhost:3000 | â Yes |
| http://localhost:3000 | http://localhost:5000 | â Different Port |
| http://localhost:3000 | https://localhost:3000 | â Different Protocol |
| http://localhost:3000 | http://example.com | â Different Host |
Common CORS Headers
| Header | Purpose |
|---|---|
| Access-Control-Allow-Origin | Specifies which origin can access the resource. |
| Access-Control-Allow-Methods | Lists the allowed HTTP methods. |
| Access-Control-Allow-Headers | Lists the allowed request headers. |
| Access-Control-Allow-Credentials | Allows cookies and authentication credentials. |
| Access-Control-Max-Age | Specifies how long preflight responses may be cached. |
Adding Basic CORS Headers
The simplest configuration allows requests from any origin by setting the Access-Control-Allow-Origin header to *.
Allow requests from any origin
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({
message: "CORS enabled"
}));
});
server.listen(3000);Warning
Allowing Specific Origins
Instead of allowing all origins, you can permit only a trusted website.
Allow a specific origin
res.setHeader(
"Access-Control-Allow-Origin",
"http://localhost:5173"
);Allowing Multiple HTTP Methods
Browsers need to know which request methods are permitted.
Allow HTTP methods
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);Allowing Request Headers
If clients send custom request headers such as Authorization or Content-Type, the server should explicitly allow them.
Allow request headers
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Authorization"
);Handling Preflight Requests
Before sending certain cross-origin requests, browsers send an OPTIONS request called a preflight request. The server must respond successfully before the browser sends the actual request.
Handle OPTIONS requests
if (req.method === "OPTIONS") {
res.writeHead(204, {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization"
});
return res.end();
}Complete Example
HTTP server with CORS support
const http = require("http");
const server = http.createServer((req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Authorization"
);
if (req.method === "OPTIONS") {
res.writeHead(204);
return res.end();
}
res.writeHead(200, {
"Content-Type": "application/json"
});
res.end(JSON.stringify({
message: "Hello from the API"
}));
});
server.listen(3000, () => {
console.log("Server running on port 3000");
});Request Lifecycle
Testing CORS
- Start the Node.js server.
- Create or open a frontend application running on a different origin.
- Send an HTTP request using fetch() or another HTTP client.
- Open the browser's Developer Tools and inspect the Network tab.
- Verify that the CORS headers appear in the response.
Example Frontend Request
Using fetch()
fetch("http://localhost:3000")
.then(response => response.json())
.then(data => {
console.log(data);
});Common CORS Errors
| Error | Cause | Solution |
|---|---|---|
| CORS policy blocked request | Missing or incorrect CORS headers | Add appropriate Access-Control-Allow-* headers. |
| Preflight request failed | OPTIONS request not handled | Return a successful response for preflight requests. |
| Header not allowed | Missing allowed request headers | Update Access-Control-Allow-Headers. |
| Method not allowed | Missing allowed methods | Update Access-Control-Allow-Methods. |
Best Practices
- Allow only trusted origins in production.
- Support preflight OPTIONS requests when necessary.
- Return only the methods and headers your API actually supports.
- Use Access-Control-Allow-Credentials only when required.
- Regularly review your CORS policy as your application evolves.
Best Practice
Official Documentation
MDN Web Docs: Cross-Origin Resource Sharing (CORS) and Node.js HTTP Module Documentation