4

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.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Hessah
  • 192
  • 3
  • 12
  • Does this answer your question? [Create-React-App Proxy in Production Build](https://stackoverflow.com/questions/45911067/create-react-app-proxy-in-production-build) – Shashoto Nur Nov 16 '21 at 11:15
  • Thanks, but it was in general which didn't help a lot... I already wrote an answer in details for this question... hopes it will help other coders too :) – Hessah Nov 16 '21 at 11:27

1 Answers1

3

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...

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Hessah
  • 192
  • 3
  • 12