Sanket Chauhan
Sanket Chauhan

Reputation: 11

Send axios (api) requests from react app deployed on heroku

In development, when i was running the react server on localhost:3000. I used proxy in package.json to set the baseurl for my backend server, which was running on loacalhost:5000. So i just edited proxy in package.json to "localhost:5000". So all the api requests sent from axios will be directed to that url.

axios.get("/name").then(res=>({...}))

A request identical to the above would be redirected to:

localhost:5000/name

In production, when i deployed the app on online platforms like heroku and vercel. The api requests sent from react-app through axios, all failed. When deploying on heroku/vercel, I changed the proxy to the online backend url.

I want to know how to change the proxy when a react app is deployed online (preferably on heroku/vercel). So that my api requests won't fail.

Tech stack: react for frontend, axios to send requests and firebase for the backend. The backend is also deployed on heroku.

Any kind of support would be appreciated. Even if there's a better platform to deploy the app, I can switch to that as well.

Upvotes: 1

Views: 3275

Answers (1)

Abhishek Singh
Abhishek Singh

Reputation: 141

You should create a config object and pick base_url based on the env. On local, it will pick development url and on Heroku it will use production.

const configs = {
  development: {
    SERVER_URI: 'localhost:5000',
  },
  production: {
    SERVER_URI: 'HEROKU_URI',
  },
};

module.exports.config = configs[process.env.NODE_ENV];

Also replace your axios calls like this:

axios.get(`${config.SERVER_URI}/name`).then(res=>({...}))

Upvotes: 2

Related Questions