How to Set Access-Control-Allow-Origin in React JS?

Tackle CORS challenges in React JS by learning how to set access-control-allow-origin header on your server or via CRA proxy for uninterrupted API calls.

Summarize with AI

Not enough time? get the key points instantly.

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 ReactJS 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 *.

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.

Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

ReactJS

Filter Items Based On Multiple Properties

Why am I getting this problem? If you apply separate filters in sequence or only check one property at a time your code will match…