The dev build works fine, with my react app on port 3000 and server on port 8080. The front end is able to make requests to the backend and get the response. But when deploying the production build, the application starts on port 5000 and the static files are rendered.But the front end can't access localhost:8080/api/:id because that port isn't 'on'. Any help will be appreciated.
0
votes
2 Answers
2
votes
You can use dotenv to define custom config variables and cross-env package to define an environment for your react application. First install these packages.
yarn add dotenv && yarn add cross-env --dev
or
npm i dotenv && npm i cross-env --dev
You need create two separate .env config files, name them as .env.development
and .env.production
. Your env file may contain something like this:
.env.development
API_URL="localhost:8080"
.env.production
API_URL="localhost:5000"
Now on your react's main.js
file(or what you have named), just import the dotenv
package as follows:
// other imports here
require('dotenv').config({
path: process.env.NODE_ENV === 'production' ? '/path/to/.env.production' : '/path/to/.env.development'
})
Now, on your package.json
, change the start and build script as such:
{
...
"scripts": {
"start": "cross-env NODE_ENV=development react-scripts start",
"build": "cross-env NODE_ENV=production react-scripts build",
...
}
...
}
Finally, wherever you have been using the API URL:
Example
axios.post(`${process.env.API_URL}/your/path`) // or any other way to join URL and path
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
Hope it helps to solve your issue.