Search code examples
reactjsdeploymentproxymernnetlify

Proxying api requests in production for React/Express app


I'm working on a MERN-stack project using separated repositories (backend & frontend), In development environment, I was using "proxy" to connect the server API with react, and it was working perfectly.

//package.json in react
{
...
"proxy": "http://localhost:8000/",
...
}

But when I switched to production environment and replaced the proxy value with the deployed link, "proxy" is no longer supported. I did a search about it and I figured out that it's only for development env, and I tried several solutions found there on the internet but with no luck!

By the way, I'm deploying the backend with Heroku, and the frontend with Netlify. Right now, both of them are deployed without any error, but there is no connection between the backend and frontend.


Solution

  • In production we can't use (proxy).. instead we can set a variable in the frontend for the backend URL, and vise versa.


    Let's start with backend configurations:

    app.use(cors({ 
       origin: "frontend_URL", 
       credentials: true 
      }));
    

    Now, let's see the frontend config:

    set a variable anywhere you prefer:

    export const API_URL = "URL";
    

    in the file where you call your API:

    import axios from "axios";
    import { API_URL } from "./your/path";
    axios.defaults.withCredentials = true;
    
    axios.get(`${API_URL}/your/route`);
    

    and now you are ready to deploy...