DEV Community

Cover image for How To Bypass CORS Error in React JS: A Practical Guide
Udemezue John
Udemezue John

Posted on

How To Bypass CORS Error in React JS: A Practical Guide

Introduction.

When working on a React project that involves fetching data from an external API, one common challenge is running into a CORS (Cross-Origin Resource Sharing) error.

This error can be incredibly frustrating, especially when everything else seems to be working fine, but the browser throws up a security wall, preventing access to the data you need.

The root cause of the CORS issue lies in the browser’s security mechanism. Browsers restrict web pages from making requests to a different domain, port, or protocol than the one the page originated from.

This restriction is a safeguard to prevent potentially malicious actions, but for developers, it often feels like an unnecessary roadblock when building legitimate applications.

Understanding why this error happens is important, but even more critical is knowing how to bypass it, especially in a development environment.

In this blog, I’ll explore practical solutions for overcoming CORS errors in a React.js app, covering both client-side workarounds and server-side fixes.

What is CORS?

CORS is a security feature implemented by web browsers to prevent one website from making requests to another domain, especially when it comes to sensitive data.

For example, if a React app running on localhost:3000 tries to fetch data from an API hosted on api.example.com, the browser blocks this request by default unless the server explicitly allows it by sending certain headers.

This is where CORS comes into play. If the API doesn’t include an Access-Control-Allow-Origin header allowing requests from your frontend, the browser will raise a CORS error, essentially saying, "I can't let you access this resource."

How Do I Bypass CORS Error in React JS?

CORS (Cross-Origin Resource Sharing) errors can be quite a headache when building a React app.

If you've ever run into the dreaded "No 'Access-Control-Allow-Origin' header" message, you're not alone.

Understanding how to handle this issue is key, especially if you're working with third-party APIs or setting up a frontend-backend architecture where your client and server are hosted on different domains.

In this article, I'll walk you through what CORS is, why it leads to errors in React, and most importantly, how to effectively bypass it.

Understanding the CORS Error in React

In a typical scenario, a React app fetches data from an API using fetch or axios. Here's an example of how a CORS error might look in a React project:

fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Enter fullscreen mode Exit fullscreen mode

If the server doesn’t send the right CORS headers, you might see an error like this in your browser's console:

Access to fetch at 'https://api.example.com/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Enter fullscreen mode Exit fullscreen mode

This happens because the API isn't configured to accept requests from localhost:3000. But how can you fix it?

Solutions for Bypassing CORS Errors in React

There are several ways to resolve CORS issues in a React app. Some involve changes on the client side, while others require modifications on the server hosting the API.

1. Use a Proxy in Development (React’s Built-in Solution).

The simplest and most effective way to handle CORS in development is to use React's built-in proxy feature. This approach is useful if you're working with a development API server.

In your package.json file, add a "proxy" field that points to the backend server. For example:

"proxy": "https://api.example.com",

Enter fullscreen mode Exit fullscreen mode

Now, when making API requests, you don't have to specify the full API URL. Instead, just use the relative path:

fetch("/data")
  .then(response => response.json())
  .then(data => console.log(data));

Enter fullscreen mode Exit fullscreen mode

React will automatically forward the requests to the specified server, bypassing CORS issues in development. However, note that this won't work in production.

2. CORS-Anywhere (Temporary Development Solution).

Another quick fix is using a service like CORS-Anywhere, which acts as a proxy server to bypass CORS issues.

You can prepend the CORS-Anywhere URL to your API requests, like this:

fetch("https://cors-anywhere.herokuapp.com/https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Enter fullscreen mode Exit fullscreen mode

This approach works well in development, but it's not a sustainable solution for production since it depends on an external service, which might not always be reliable.

3. Modify Server-Side Headers.

If you have control over the backend server, the best and most permanent fix is to modify the server to include CORS headers.

The server needs to send an Access-Control-Allow-Origin header that allows your frontend's domain.

For example, in an Express.js backend, you could enable CORS like this:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

app.get('/data', (req, res) => {
  res.json({ data: "Some data" });
});

app.listen(3001, () => {
  console.log('Server is running on port 3001');
});

Enter fullscreen mode Exit fullscreen mode

The cors middleware automatically sets the necessary headers, allowing your frontend to access resources from the backend.

4. Configure Headers in Cloud-Based APIs (AWS, Firebase, etc.).

If you’re using cloud-based services like AWS API Gateway or Firebase, CORS settings are often part of the API's configuration.

  • AWS API Gateway: In AWS API Gateway, you can enable CORS directly through the console by selecting the API resource and enabling CORS for it. AWS will automatically add the appropriate headers.
  • Firebase Functions: In Firebase, you can enable CORS by manually adding headers in the function's response, like so:
const functions = require('firebase-functions');
const cors = require('cors')({origin: true});

exports.myFunction = functions.https.onRequest((req, res) => {
  cors(req, res, () => {
    res.status(200).send("CORS-enabled response");
  });
});
Enter fullscreen mode Exit fullscreen mode

5. Use http-proxy-middleware in React for More Complex Proxies.

If you're working with more complex backend setups or need finer control over your proxy behavior, using http-proxy-middleware is a great option.

First, install the package:

npm install http-proxy-middleware --save

Enter fullscreen mode Exit fullscreen mode

Then, create a src/setupProxy.js file in your React project and configure the proxy like this:

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'https://api.example.com',
      changeOrigin: true,
    })
  );
};

Enter fullscreen mode Exit fullscreen mode

Now, any request made to /api will automatically be proxied to https://api.example.com, bypassing CORS.

6. Use Browser Extensions (Last Resort).

As a last resort, you could use browser extensions to bypass CORS errors. These extensions work by adding the necessary headers client-side, but they should only be used in development environments. One popular extension is Allow CORS: Access-Control-Allow-Origin.

However, using browser extensions to bypass CORS is not recommended for production environments, as it creates a potential security risk.

When Not to Bypass CORS.

It’s essential to remember that CORS is there for a reason — to protect users and resources from malicious behavior.

While it’s fine to bypass CORS in a controlled development environment, you should never attempt to disable it or circumvent it in production by using hacks like CORS-Anywhere.

The right solution is always server-side. Either ensure the backend sends the proper CORS headers or configure your backend and frontend to work on the same origin.

Conclusion.

CORS errors are a common issue when working with React, but there are several ways to handle them depending on your setup.

For development, using a proxy or services like CORS-Anywhere can be a quick fix.

But for production, the best practice is always to ensure that the backend is configured correctly to handle CORS requests by adding the appropriate headers.

Top comments (0)