I'm building web app with React frontend and Node.js backend (API).
In React frontend I call API methods like this:
axios({
method: 'post',
url: 'http://servername:9999/reports.activities',
data: {
user_id: 1
}
}).then(res => {
this.setState(res.data);
});
Sometimes I need to test API methods that is not released to production yet.
When I test backend locally, i run nodemon api.js
on localhost:9999
.
Every time I want to test frontend with local-running API, I have to change http://servername:9999
to http://localhost:9999
in my frontend code.
I think this is not the right approach.
What is the best way to use different url for development (when run npm start
locally) and production (npm build
)?
I was thinking of using dotenv for this purpose. Is this the right approach?
What is the best practice?
First, you import React and Axios so that both can be used in the component. Then you hook into the componentDidMount lifecycle hook and perform a GET request. You use axios. get(url) with a URL from an API endpoint to get a promise which returns a response object.
To store the API keys, create a new file called . env in the root directory of the React application. You can now access the API key in any file in the React app using process. env.
If you are using create-react-app you have already dotenv installed.
https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env
So you can so:
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT || 'http://production';
...
url: `${API_ENDPOINT}/reports.activities`
You can create 2 .env
files called .env.development
and .env.production
.
//.env.development
REACT_APP_API_ENDPOINT=http://localhost:9999
//.env.production
REACT_APP_API_ENDPOINT=https://servername:9999
Then use it as follows -
//api.js
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT
axios({
method: 'post',
url: `${API_ENDPOINT}/reports.activities`,
data: {
user_id: 1
}
}).then(res => {
this.setState(res.data);
});
The way it works is: when you run npm start
, react will use the .env.development
file and when you do npm run build
, react will use the .env.production
file.
Here's the relevant part of the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With