JIYIK CN >

Current Location:Home > Learning > NETWORK >

How to avoid cross-origin (CORS) issues in React/Next.js

Author:JIYIK Last Updated:2025/03/17 Views:

If you’ve written any front-end code, you’ve probably encountered a CORS error before, like this:

Access to _ has been blocked by CORS policy

Cross-Origin Resource Sharing (CORS) is a protocol that defines how web requests should be handled when they cross different URLs.


Why are cross-origin requests a problem?

For every website we visit, our browser saves a lot of state about us. Let's say we are logged in mybank.com, and we mybank.comset a cookie on that indicates that we are logged in.

While browsing, we accidentally visited a malicious website that made the following request to mybank.com:

// 从 https://malicious.site 获取请求
fetch("https://api.mybank.com/account_details", {
    method: "GET",
    credentials: "include",
})

If this request is allowed and our cookies are included, the owner of the malicious website will be able to make requests on our behalf and read our account details.

Using CORS allows the server to specify which cross-origin requests it will accept and deny. It can deny requests that require cookies. It can deny requests from untrusted.mybank.com but accept requests from app.mybank.com. It can deny all POST requests but allow GET and PUT.

The important thing to note about CORS is that the configuration/setup is done on the server and is enforced by the server and our browser. Most server frameworks have a library for configuring CORS headers, but if we want to look at the underlying headers themselves, here is a great resource.


Practical Examples

Let's say we have a React application with an Express backend. Our frontend is running on port 3000 - a common default for React.

Since our backend can't run on port 3000 locally either, we'll set up Express to run on port 4000.

const express = require('express')
const app = express()
const port = 4000
app.get('/whoami', (req, res) => {
    res.send('Who is anybody?')
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

If our React application makes a fetch request to our backend like this:

// 获取来自 http://127.0.0.1:3000 的请求
fetch("http://127.0.0.1:4000/whoami")

We should expect a CORS error. Just like our previous example, 127.0.0.1:3000 and 127.0.0.1:4000 are treated as two separate domains, so we can't make requests across them yet. Let's look at some ways to fix this.

Fix 1: Repair the server

One way to do this is to fix our server. We can https://www.npmjs.com/package/corsdo this by installing the CORS library ( ) and telling the server to expect requests from 127.0.0.1:3000

app.use(cors({
    origin: 'http://127.0.0.1:3000',
}))

Our request will now succeed. This approach is very simple and is generally good practice. We can use the same approach in production if our frontend and backend are hosted on two different subdomains.

Fix 2: Add a proxy

In production, in some cases we will host our frontend and backend from the same origin. In these cases, we usually want to write fetch code like this:

fetch("/whoami")

Instead of this:

const url;
if (process.env.NODE_ENV === "production") {
    url = "https://www.example.com/whoami"
} else {
    url = "http://127.0.0.1:4000/whoami"
}
fetch(url)

To do this, create-react-appwe actually have the ability to set up a simple proxy built in. Add the following to our package.json:

"proxy": "http://localhost:4000",

Then, any request that looks like an API request (eg, has a content-type of application/json) is automatically forwarded to http://localhost:4000.

What gets around the CORS issue is that to the browser the request is going to http://localhost:3000, so it doesn't look like a cross-origin request. http://localhost:3000's server does forward the request to http://localhost:4000, but the browser doesn't know that.

If we were using Next.js instead of create-react-app, we could set up a redirect in next.config.js and it would forward all matching traffic:

module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*',
        destination: 'http://localhost:4000/:path*'
      }
    ]
  }
}

Summarize

The easiest way to fix any CORS issues in React and Next.js is actually to not change anything in React or Next.js, but to fix our servers to allow requests from them.

If we can’t change the server, both React and Next.js have ways for us to turn them into proxies and proxy the requests to the backend on our behalf. This avoids any CORS issues by making our browser think the request is no longer a cross-origin request.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to fix cross-origin (CORS) issues in Angular

Publish Date:2025/03/17 Views:192 Category:NETWORK

When we use a backend server for our Angular application during development, when trying to request resources from the API, we may encounter some cross-origin (CORS) restrictions that prevent us from accessing data from the API.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:185 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:183 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:99 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:187 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial