
How to Fix CORS Error in React and Express (Step-by-Step 2026 Guide)
Have you ever built a React application, connected it to an Express backend, and suddenly seen a CORS error in your browser? Your API may work perfectly in Postman, but when you try to fetch data from your React frontend, the browser blocks access to the response.
This is a common problem for developers learning full-stack web development. The good news is that you can usually fix it by configuring your Express server correctly.
In this guide, you will learn what CORS means, why it happens, how to fix it step by step, and how to troubleshoot common problems using practical code examples.
Whether you are building a portfolio website, a dashboard, a login system, or a full-stack application, this tutorial will help you understand the problem instead of simply copying a solution.
What Is a CORS Error?
CORS stands for Cross-Origin Resource Sharing. It is a browser security mechanism that allows a server to specify which website origins can read its responses.
For example, imagine your project runs at these addresses:
- React frontend:
http://localhost:5173 - Express backend:
http://localhost:5000
Although both applications run on your computer, they use different ports. That means they have different origins.
An origin consists of the scheme, hostname, and port. If any of these differ, the origins are different.
When React sends a request to Express, the browser checks whether the backend response contains the appropriate CORS headers. If the required permission is missing or incorrect, JavaScript cannot read the response.
You can learn more from the official MDN guide to Cross-Origin Resource Sharing.
Why Does CORS Happen in React and Express?
Several issues can cause a CORS error in a full-stack application.
1. The Express server does not allow your frontend origin. The backend may not be configured to accept browser requests from your React development server.
2. The frontend uses the wrong API URL. Your React app might be sending requests to the wrong port, an outdated URL, or a server that is not running.
3. The browser’s preflight request fails. Some requests require an initial OPTIONS request to check whether the actual request is permitted.
4. Credentials are configured incorrectly. Requests using cookies or HTTP authentication require compatible CORS settings.
5. Your backend returns an error without the required headers. An exception, redirect, or proxy response can make a request appear to have a CORS problem when another server issue is also involved.
Understanding which situation applies to your project makes the fix much easier.
How to Fix CORS Error in React and Express Step by Step
Let’s use a simple example with a React frontend and an Express backend.
Step 1: Check Your Project Structure
A typical project might look like this:
my-fullstack-app/
├── client/
│ ├── src/
│ │ ├── App.jsx
│ │ └── main.jsx
│ └── package.json
│
└── server/
├── server.js
└── package.json
Your project may use different filenames or folders. That is fine; the important thing is to locate your Express entry file and the React component making the API request.
Step 2: Install the Express CORS Package
Open a terminal in your backend folder, where the Express package.json file is located.
Run:
npm install cors
The cors package is middleware for Node.js and Express that adds the appropriate CORS response headers.
Official documentation: Express CORS middleware.
Step 3: Configure CORS in Your Express Server
Open your backend’s server.js file.
If you are using CommonJS (require), use this example:
const express = require("express");
const cors = require("cors");
const app = express();
const PORT = 5000;
// Allow requests from your React development server
app.use(
cors({
origin: "http://localhost:5173",
})
);
app.use(express.json());
// Example API route
app.get("/api/message", (req, res) => {
res.json({
message: "React and Express are connected successfully!",
});
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Important: Put the CORS middleware before your API routes. This helps ensure that the middleware handles the relevant requests and adds the necessary headers.
If your React development server runs on another port, replace http://localhost:5173 with the exact origin shown in your browser’s address bar.
For example, if Vite starts at http://localhost:5174, your allowed origin must match that address.
Step 4: Start the Express Backend
Open a terminal in the backend folder and run:
node server.js
If your project uses a development script, you may instead run:
npm run dev
Use the command configured in your own package.json.
You should see a message similar to:
Server running on http://localhost:5000
Now open this URL in your browser:
http://localhost:5000/api/message
You should receive a JSON response:
{
"message": "React and Express are connected successfully!"
}
This confirms that the example endpoint is responding. It does not, by itself, prove that every cross-origin request is configured correctly, so test from React next.
Step 5: Send a Request From React
Open your React component, such as client/src/App.jsx.
Replace the example component with the following:
import { useEffect, useState } from "react";
function App() {
const [message, setMessage] = useState("");
const [error, setError] = useState("");
useEffect(() => {
fetch("http://localhost:5000/api/message")
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => {
setMessage(data.message);
})
.catch((err) => {
console.error("API request failed:", err);
setError(
"Could not connect to the backend. Check the server and browser console."
);
});
}, []);
return (
<main>
<h1>React and Express Connection</h1>
{message && <p>{message}</p>}
{error && <p role="alert">{error}</p>}
</main>
);
}
export default App;
Make sure the backend URL matches the port where your Express server is running.
Start the frontend in a separate terminal:
npm run dev
Open the Vite URL shown in your terminal. If everything is configured correctly, your page should display:
React and Express are connected successfully!
If the request still fails, continue with the troubleshooting section below rather than changing random settings.
Step 6: Allow More Than One Frontend Origin
During development, you might use different frontend addresses, such as a local Vite server and a separate local testing environment.
You can allow a specific list of origins:
const allowedOrigins = [
"http://localhost:5173",
"http://localhost:3000",
];
app.use(
cors({
origin: allowedOrigins,
})
);
This configuration permits the listed origins, not every website on the internet.
If your application uses another port, add its exact origin to the list. Do not include a URL path such as /dashboard because an origin contains only the scheme, hostname, and port.
For a deployed application, use your actual frontend domain, for example:
const allowedOrigins = [
"http://localhost:5173",
"https://your-frontend-domain.com",
];
Replace the example domain with your real website address.
Step 7: Fix CORS Errors Involving POST Requests
A React application may send a POST request containing JSON data. This often triggers a browser preflight request because application/json is not a CORS-safelisted content type.
For example, your frontend might send:
fetch("http://localhost:5000/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "Alex",
}),
});
Your Express server should allow the relevant origin and method:
app.use(
cors({
origin: "http://localhost:5173",
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
})
);
The cors middleware handles preflight requests for routes when it is installed at application level with app.use(cors(...)).
If you apply CORS only to selected routes, ensure that the relevant OPTIONS preflight request is handled too. See the official Express CORS documentation for route-level configuration.
Do not assume every failed POST request is a CORS issue. Check the browser’s Network panel to see whether the preflight request failed or the actual API request returned an error.
Step 8: Fix CORS Errors When Using Cookies
Some applications use cookies for authentication. In that case, both the frontend and backend need compatible credentials settings.
On the Express side:
app.use(
cors({
origin: "http://localhost:5173",
credentials: true,
})
);
On the React side:
fetch("http://localhost:5000/api/profile", {
method: "GET",
credentials: "include",
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((error) => console.error(error));
For credentialed browser requests, the server must return an explicit allowed origin and Access-Control-Allow-Credentials: true.
Do not combine credentialed requests with Access-Control-Allow-Origin: *. Browsers reject that combination.
Also remember that CORS settings alone do not guarantee that cookies will be sent. Cookie attributes, HTTPS, and browser privacy rules can affect whether cookies are included.
Step 9: Fix CORS Errors After Deployment
A project that works locally can fail after deployment because its frontend and backend now have different production URLs.
For example:
- Frontend:
https://your-frontend-domain.com - Backend:
https://your-api-domain.com
Your production Express server must allow the production frontend origin, not only localhost.
A simple production configuration could be:
const allowedOrigins = [
"https://your-frontend-domain.com",
];
app.use(
cors({
origin: allowedOrigins,
})
);
If you also need local development, include your local frontend origin in the list.
For a Vite frontend, store the API URL in an environment variable:
VITE_API_URL=https://your-api-domain.com
Then use it in React:
const API_URL = import.meta.env.VITE_API_URL;
fetch(`${API_URL}/api/message`)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.error(error));
Restart the Vite development server after changing local environment variables. In production, configure the variable in your hosting platform and rebuild or redeploy the frontend if required.
Security note: Vite variables prefixed with VITE_ are exposed to frontend code. Never put database passwords, private API keys, or other secrets in them.
Common CORS Errors and Their Solutions
| Error or symptom | What to check |
|---|---|
No 'Access-Control-Allow-Origin' header |
Add the correct frontend origin to the backend’s CORS configuration. |
| Allowed origin does not match | Compare the exact scheme, hostname, and port. |
Response to preflight request doesn't pass access control check |
Inspect the OPTIONS request, allowed methods, and allowed headers. |
| Wildcard origin with credentials | Replace * with the specific frontend origin and enable credentials when needed. |
Failed to fetch |
Check the console, Network panel, backend availability, URL, and CORS response. |
| Works locally but fails in production | Update the production origin, API URL, HTTPS configuration, and hosting settings. |
404 Not Found |
Confirm that the API route and request path exist. |
500 Internal Server Error |
Inspect backend logs; the server may have failed while handling the request. |
A 404, 500, or network failure is not automatically a CORS configuration problem. Diagnose the actual request and response before making changes.
How to Debug a CORS Error in Chrome
If the problem continues, use your browser’s developer tools.
- Open your React application in Chrome.
- Press
F12or right-click the page and select Inspect. - Open the Console tab and reproduce the error.
- Open the Network tab.
- Find the failed API request. Check its Request URL, status code, response headers, and any preceding
OPTIONSrequest. - Look at your Express terminal for errors.
- Compare the request’s
Originheader with the origin configured in your backend.
This approach helps distinguish a missing CORS header from a wrong URL, a stopped backend, a failed preflight request, or a server-side error.
For more details, see MDN’s CORS troubleshooting guide.
Mistakes to Avoid When Fixing CORS
Using mode: "no-cors" as a general fix: This mode produces an opaque response that JavaScript cannot read normally. It does not solve a typical React-to-Express JSON API problem.
Allowing every origin unnecessarily: cors() or origin: "*" may be suitable for a genuinely public API, but private or credentialed endpoints generally need more restrictive configuration.
Adding CORS middleware after every route: If the middleware runs too late, some responses may not receive the expected headers.
Changing React code when the backend controls the missing headers: Most CORS configuration problems need to be addressed by the server that serves the API response.
Treating CORS as authentication: CORS is enforced by browsers. It does not prevent direct requests from tools or other servers. Protect private APIs with proper authentication and authorization.
Frequently Asked Questions
1. Why does React show a CORS error when Express works in Postman?
Postman is not a browser and does not enforce browser CORS rules. Your Express API may respond successfully in Postman while its response headers remain unsuitable for your React application’s origin.
2. Is CORS a React problem or an Express problem?
In a React-to-Express application, the server usually needs to provide the correct CORS headers. React can send requests to the correct endpoint, but it cannot override the browser’s CORS enforcement.
3. Does installing the cors package fix every CORS error?
No. Installing the package is only the first step. You must configure the correct origins and, when necessary, credentials, methods, and headers. Server failures, redirects, and incorrect URLs can also cause requests to fail.
4. Can I use CORS with Vite?
Yes. Vite can run your React frontend on a different port from your Express backend. Configure Express to allow the exact Vite origin shown in your terminal.
5. Should I use origin: "*" in production?
Only when broad access is appropriate for your API. Avoid wildcard origins for private APIs and credentialed requests. Prefer explicitly allowing the frontend domains that need access.
6. Why does my CORS error happen only after deployment?
Your production frontend probably has a different origin from your local development server. Update the backend’s CORS configuration and verify that the frontend is using the correct deployed API URL.
7. Does CORS protect my backend from hackers?
No. CORS controls whether browser JavaScript can read a response from another origin. Use authentication, authorization, input validation, rate limiting, and other appropriate security measures to protect your backend.
Final Thoughts
Fixing a CORS error in React and Express becomes much easier once you understand the relationship between browser security and server response headers.
Start by confirming your API URL, install the Express cors middleware, allow the correct frontend origin, and test the request in your browser. If the error remains, inspect the Network panel and backend logs instead of blindly changing configuration.
These steps will help you debug many common CORS problems in local development and deployed full-stack applications.
Keep learning, keep building, and keep debugging. Every error you solve makes you a stronger web developer.
