Introduction
Cross‑Origin Resource Sharing (CORS) errors are a common headache when building APIs with Node.js and consuming them from browsers or other services. This guide walks you through the quickest ways to identify, troubleshoot, and permanently fix CORS issues in a Node.js Fast setup.
What Is CORS?
CORS is a browser security mechanism that restricts web pages from making requests to a different origin (scheme, host, or port) than the one that served the page. The server must explicitly allow the request by sending appropriate HTTP headers.
Typical Scenarios That Trigger CORS Errors
- Missing
Access-Control-Allow-Originheader -
Mismatched HTTP methods (e.g., POST without
Access-Control-Allow-Methods) -
Credentials flag –
Access-Control-Allow-Credentialsmust be true and the origin cannot be*. - Pre‑flight (
OPTIONS) requests not handled
Quick Fix Using the cors Middleware
The easiest and most reliable solution is to add the official cors package.
npm install cors --save
// server.js
const express = require('express');
const cors = require('cors');
const app = express();
// Basic usage – allow any origin (good for development)
app.use(cors());
// Advanced configuration – restrict to specific origins and enable credentials
const corsOptions = {
origin: ['https://example.com', 'https://app.example.org'],
methods: ['GET','POST','PUT','DELETE'],
credentials: true,
allowedHeaders: ['Content-Type','Authorization']
};
app.use(cors(corsOptions));
app.get('/api/data', (req, res) => {
res.json({msg: 'CORS is working!'});
});
app.listen(3000, () => console.log('Server listening on port 3000'));
Tip: Keep the middleware as the first
app.usecall so that every route inherits the CORS headers.
Manual Header Setup (When You Can't Use Middleware)
If you need fine‑grained control or are using a minimal framework, set the headers yourself:
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'https://example.com');
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
res.setHeader('Access-Control-Allow-Credentials', 'true');
// Handle pre‑flight requests
if (req.method === 'OPTIONS') {
return res.sendStatus(204);
}
next();
});
Step‑by‑Step Troubleshooting Checklist
- Open the browser console – note the exact error message.
- Inspect the network tab – check the response headers of the failing request.
-
Confirm the server sends
Access-Control-Allow-Originmatching the request'sOriginheader. - Verify the pre‑flight
OPTIONSrequest receives a204or200status with proper headers. -
If credentials are involved, ensure
Access-Control-Allow-Credentials: trueand that the origin is not*. - Check proxy configurations (NGINX, Apache, Docker) that might strip CORS headers.
Advanced: Using a Reverse Proxy to Inject CORS Headers
When you cannot modify the Node.js code directly, a reverse proxy can add the required headers.
# nginx.conf snippet
location /api/ {
proxy_pass http://localhost:3000;
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
if ($request_method = OPTIONS) {
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
}
Testing Your Fix
# Simple curl test (no browser CORS enforcement)
curl -i -H "Origin: https://example.com" http://localhost:3000/api/data
You should see:
HTTP/1.1 200 OK
Access‑Control‑Allow‑Origin: https://example.com
Access‑Control‑Allow‑Credentials: true
...
If the headers appear, the browser will no longer block the request.
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
Using * with credentials |
Browser blocks it | Specify explicit origin |
Forgetting to handle OPTIONS
|
Pre‑flight fails | Return 204 with headers |
| Proxy strips headers | Mis‑configured proxy | Add proxy_set_header or add_header rules |
Conclusion
CORS errors can be eliminated in minutes with the right middleware or header configuration. Start with the cors package for rapid development, then move to manual or proxy solutions for production‑grade control.
Resources & Tools
- Download the pre‑configured script here: Download the pre-configured script here
- Get the complete patch tool: Get the complete patch tool
- Access the full repository fix: Access the full repository fix
Happy coding!
Top comments (0)