AWS Builder Center
Understanding CORS in Web Development: Why Your Frontend Can't Talk to Your Backend

Understanding CORS in Web Development: Why Your Frontend Can't Talk to Your Backend

Exploring CORS properties and solving problems.

Exploring Web Development and Cloud Computing

Understanding CORS in Web Development: Why Your Frontend Can't Talk to Your Backend

Have you ever built a React application, connected it to a Node.js backend, and suddenly encountered an error saying:
 Access to fetch at ... has been blocked by CORS policy 
If you've experienced this, you're not alone.
CORS is one of those concepts that almost every frontend or full-stack developer encounters, but it can be confusing when you're first learning how frontend and backend applications communicate.
Let's understand what CORS is, why browsers enforce it, and how to handle it properly in a real-world application.

1. What Exactly Is CORS?

CORS stands for Cross-Origin Resource Sharing.
It is a browser security mechanism that controls whether a web application running on one origin can access resources from another origin.
First, let's understand what an origin means.
An origin consists of three components:
  • Protocol (HTTP or HTTPS)
  • Domain (example.com)
  • Port (3000, 5000, etc.)
For example:
Frontend: http://localhost:5173
Backend: http://localhost:5000
Although both applications are running on localhost, their ports are different. Therefore, they have different origins.
By default, browsers follow a security mechanism called the Same-Origin Policy, which restricts JavaScript from accessing resources from a different origin.
This is where CORS comes into the picture.
CORS allows servers to explicitly specify which origins are permitted to access their resources.

2. Why Do We Need CORS?

Imagine you're building a full-stack application using React and Node.js.
Your React application runs on:
http://localhost:5173
Your Express backend runs on:
http://localhost:5000
Now, your frontend tries to retrieve user information:
fetch("http://localhost:5000/api/users")
.then(response => response.json())
.then(data => console.log(data));
The browser checks whether the backend allows requests from the frontend's origin.
If the appropriate CORS headers are missing, the browser prevents your frontend JavaScript from accessing the response.
You might see an error similar to:
Access to fetch has been blocked by CORS policy.
The important thing to understand is that CORS is enforced by browsers, not by React or Express themselves.
It helps prevent malicious websites from freely reading responses from other websites using your browser's authenticated session.

3. How Does CORS Work?

Let's understand the communication flow.
When a browser sends a cross-origin request, the server can respond with an HTTP header such as:
Access-Control-Allow-Origin: http://localhost:5173
This tells the browser that the specified origin is allowed to access the response.
The process looks like this:
React Frontend
|
| API Request
v
Express Backend
|
| Checks and responds with CORS headers
v
Browser
|
| Validates CORS permissions
v
Frontend receives the response
If the server doesn't provide the required permissions, the browser blocks JavaScript from accessing the response.

4. Understanding Preflight Requests

This is another important concept in CORS.
Not every cross-origin request works in exactly the same way.
For certain requests, the browser first sends an HTTP OPTIONS request called a preflight request.
For example, suppose you're sending user information using a POST request with JSON:
fetch("http://localhost:5000/api/users", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John",
email: "john@example.com"
})
});
Because this request uses  Content-Type: application/json , it generally triggers a preflight request.
The browser first asks the server whether the actual request is permitted.
A simplified flow looks like this:
Browser
|
| OPTIONS Request
v
Backend
|
| Allows POST and required headers
v
Browser
|
| Actual POST Request
v
Backend
|
| Returns Response
v
Browser
Some common CORS response headers include:
  •  Access-Control-Allow-Origin : Specifies permitted origins.
  •  Access-Control-Allow-Methods : Specifies permitted HTTP methods.
  •  Access-Control-Allow-Headers : Specifies permitted request headers.
  •  Access-Control-Allow-Credentials : Indicates whether credentials can be included in cross-origin requests.
Understanding preflight requests makes debugging CORS errors much easier.

5. How to Fix CORS in a Node.js and Express Application

Now let's implement CORS in a practical example.
Suppose we have a React frontend and an Express backend.
First, install the CORS package:
npm install cors
Next, configure it in your Express application:
const express = require("express");
const cors = require("cors");

const app = express();

app.use(cors({
origin: "http://localhost:5173"
}));

app.use(express.json());

app.get("/api/users", (req, res) => {
res.json({
message: "Users fetched successfully"
});
});

app.listen(5000, () => {
console.log("Server running on port 5000");
});
Here is what happens:
  1. We import the CORS package.
  1. We configure the frontend origin that is allowed to access our backend.
  1. Express handles the necessary CORS headers.
  1. Our React application can now make permitted cross-origin API requests.
For production applications, it's better to configure allowed origins using environment variables rather than hardcoding development URLs.

6. Common CORS Mistakes Developers Make

Even after understanding CORS, developers frequently encounter problems because of incorrect configurations.
Here are some common mistakes:
Mistake 1: Allowing every origin in production
Using  origin: "*"  might seem like an easy solution, but it is not suitable for every application.
You should explicitly allow trusted origins, especially when dealing with authenticated APIs.
Mistake 2: Using credentials with a wildcard origin
If your application uses cookies for authentication, you might configure:
app.use(cors({
origin: "http://localhost:5173",
credentials: true
}));
Your frontend must also include credentials:
fetch("http://localhost:5000/api/users", {
credentials: "include"
});
When credentials are enabled, the server cannot use  Access-Control-Allow-Origin: * . It must return a specific allowed origin.
Also, remember that cookie attributes such as  SameSite  and  Secure  can affect whether cookies are sent.
Mistake 3: Trying to fix CORS from the frontend
CORS permissions are primarily configured on the server.
Changing React code or adding random request headers will not solve an incorrectly configured backend.

7. CORS Is Not a Replacement for Authentication

One important thing to remember is that CORS does not protect your backend from every unauthorized request.
It controls whether browser-based JavaScript from another origin can access a response.
It does not prevent requests from tools such as Postman, curl, or other servers.
Therefore, your backend should still implement proper authentication, authorization, input validation, and other security measures.
Never rely on CORS alone to protect sensitive APIs.

Conclusion

CORS might initially look like an annoying obstacle when connecting frontend and backend applications, but it serves an important purpose in browser security.
Once you understand origins, preflight requests, and server-side CORS configuration, debugging these errors becomes much easier.
As developers, we should not simply copy a CORS configuration whenever an error appears. Instead, we should understand why the browser is blocking a request and configure our backend accordingly.
The next time you connect a React frontend to an Express backend, you'll know exactly what is happening behind the scenes.
Understanding these fundamentals is an important step toward becoming a better full-stack developer.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article