CORS error: No 'Access-Control-Allow-Origin' header is present on the requested resource
Quick answer
Your backend isn't sending CORS headers that allow your frontend's origin. Install and configure the `cors` package with your frontend's exact URL(s), and make sure it's applied before your routes are registered.
What causes this error
Browsers block cross-origin requests by default unless the server explicitly allows them via CORS headers. This isn't a bug in your fetch call — it's the server's responsibility to opt in.
The Fix
import cors from 'cors';
app.use(cors({
origin: ['http://localhost:3000', 'https://yourdomain.com'],
credentials: true,
}));
// This must come BEFORE your route definitions
app.use('/api', routes);Common causes / variations
- `cors()` middleware registered after your routes instead of before
- Origin mismatch — `http://localhost:3000` vs `http://127.0.0.1:3000` are different origins
- Forgetting to update allowed origins after deploying to a new production domain
- Using `credentials: true` on the frontend but not matching it on the backend's CORS config (wildcard `*` origin doesn't work with credentials)
Related errors
See also: req.body is undefined, environment variable not found.
Was this fix helpful?
Comments
Loading comments...