Fixing CORS Errors with React Proxy: A Simple Solution

MedsMeds
3 min read

A lot depends on what you use as your development environment, the traditional Create-react-app or the new trend Vite. I prefer Vite, it stands out because it’s remarkably fast and sets up very quickly, which is a big advantage.

Now if you’re building a web application using React, which is a popular JavaScript library. Your app might need to talk to a server to fetch data or perform actions, like sending and receiving information.
However, when your React app on one domain (like localhost, where you’re developing your app) tries to communicate with a server on a different domain (like an API server), it often encounters security restrictions known as CORS (Cross-Origin Resource Sharing) issues. These restrictions are in place to prevent potential security risks.

You can set up a “proxy” that acts as a middleman between your React app and the API server.

In this article, I’ll be covering how to setup a proxy server in Vite and later in Create-react-app.

Remember to replace http://localhost:8800 with the actual URL of your backend server, Since I’m using port 8800 in my backend server example, this code works for me.

VITE

Unlike how we do it in create- react- app, we’re going to make changes in vite.config.js of our react_app (name of the folder).
Below is a screenshot applied for better understanding.

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({ 
  server: {
    proxy: {
      "/api": "http://localhost:8800",
    }  
  } ,
  plugins: [react()],
})
  1. export default defineConfig({ ... }): This part is configuring the default settings for your Vite project.

  2. server: { ... }: Within the configuration, you're specifying settings related to the development server.

  3. proxy: { ... }: Inside the server settings, you're setting up a proxy configuration. This is where you define what URLs your app should proxy to another server.

  4. "/api": "http://localhost:8800": You're saying that whenever your React app tries to make a request to a URL that starts with "/api", the development server should forward that request to http://localhost:8800. This is helpful because your API server might be running on a different port (8800 in this case), and without this proxy, you could run into CORS issues.

  5. plugins: [react()],: This part is adding a React plugin to your Vite configuration, which helps Vite understand and handle React components.

In the web application I was developing, I had to perform a GET request, and here’s how I went about it:

const getPins = async () => {
      try {
        const allPins = await axios.get("/api/pins");
        setPins(allPins.data);
      } catch (err) {
        console.log(err);
      }
    };

Create-react-App

In Create React App, you can set up a proxy for development directly in the package.json file. Just add this one more dependency in that long list present in your package.json file.

{
   "proxy": "http://localhost:8800",
}

Now, if your React app makes a request to /api/pins, and the development server doesn't have a corresponding route, it will forward the request to http://localhost:8800

30
Subscribe to my newsletter

Read articles from Meds directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Meds
Meds

I am an aspiring technical writer who enjoys listening to others, as it helps me gain new insights. I strongly believe that effective communication is at the core of success for any leader and business.