Reputation: 321
I finished my app and want to deploy it to Heroku. I've got calls to api (on the local machine) that looks like this
const isDeleted = await request(
"DELETE",
`/api/me/posts/${postId}`
);
In develpoment they were proxied in package.json
like this
"proxy": "http://localhost:4000"
I've found solution that suggest creating a file with constants and exporting url
conditionally, sth like this:
exports = isProduction ? 'api/production' : 'http://localhost:300'
And then prefixing all my calls with that const, but it does not feel right and I think there is a cleaner way to do it.
Upvotes: 1
Views: 2249
Reputation: 321
Heroku has its own env variables. They are called config vars. See here.
Even though they are Heroku envs, they still have to be prefixed with REACT_APP
. Otherwise React will not pick them up.
I prefixed all my calls with REACT_APP_API
and it worked.
Upvotes: 1
Reputation: 3988
In ReactJs, you can use environment variable to production and development server differently.
Create .env file and .env.production in root directory of projects.
1. It is necessary to use REACT_APP_{Your custom variable name} syntax to pick up by react server.
REACT_APP_BACKEND_URL=https://localhost/
REACT_APP_BACKEND_URL=https://online-exam-mern.herokuapp.com/
const response = await fetch(
`${process.env.REACT_APP_BACKEND_URL}admin/auth/login`,
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
email,
password
})
}
);
The react will automatically pick .env.production file variable when you build your projects using npm run build, whereas during development it will use variable from .env file
Upvotes: 2