You can’t set CORS response headers from React (client-side). Browsers enforce CORS based on the server, so you must configure your API server or use a development proxy to set the Access-Control-Allow-Origin header.
1. Use a Development Proxy (Create React App)
In development, proxy API requests to avoid CORS errors without touching server code:
// package.json{
// …
“proxy”: “http://localhost:5000”
}
- Any request from http://localhost:3000/api/… goes to your backend on port 5000.
- Browser treats it as same-origin, so no CORS in development.
2. Configure Your Server to Send CORS Headers
Express.js Example
// server.jsimport express from ‘express’;
import cors from ‘cors’;
const app = express();
// Allow all origins (or replace ‘*’ with your React app URL)
app.use(cors({ origin: ‘*’ }));
app.get(‘/api/data’, (req, res) => {
res.json({ message: ‘Hello from server!’ });
});
app.listen(5000, () => {
console.log(‘Server running on port 5000’);
});
- cors({ origin: ‘*’ }) adds Access-Control-Allow-Origin: *
- For production, specify your exact React app domain instead of *.
Also Read: ReactJS Material Design
3. NGINX Configuration (Optional)
If you’re hosting on NGINX, add in your server block:
location /api/ { add_header Access-Control-Allow-Origin https://your-app.com;
add_header Access-Control-Allow-Methods ‘GET, POST, OPTIONS’;
add_header Access-Control-Allow-Headers ‘Origin, Content-Type, Accept’;
}
Why This Works?
- Client can’t set CORS headers: only servers can.
- CRA proxy makes dev requests look same-origin to the browser.
- Server middleware (Express/NGINX) sets the Access-Control-Allow-Origin header so browsers allow cross-origin responses.