⚡TL;DR
Quickly fix CORS errors in your API by enabling cross-origin requests with a simple middleware.
Problem:
You are getting this error in frontend:
"Access to fetch at 'API_URL' from origin 'http://localhost:3000' has been blocked by CORS policy"
Fix (1 line):
Install CORS:
npm install cors
Enable it in your Express app:
JavaScript
const cors = require('cors');
app.use(cors());That's it — your API will now accept requests from any origin.
---
More Secure Option (Recommended for production):
JavaScript
app.use(cors({
origin: 'http://localhost:3000'
}));You can also allow multiple domains:
JavaScript
app.use(cors({
origin: ['http://localhost:3000', 'https://yourdomain.com']
}));---
Bonus Tip:
If you're using credentials (cookies/auth), enable:
JavaScript
app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}));CORSmiddlewareExpress BackendFix
⚡
Get a new 1-Min Fix in your inbox
Subscribe to Stack Dev Life — free, no spam, unsubscribe anytime.
Subscribe free →