17

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?

3 Answers 3

17

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.

Sign up to request clarification or add additional context in comments.

1 Comment

do we need to add the //.env.development and //.env.production in the .gitignore?
12

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`

Comments

0

If you swict to vite you can use. Default vite expose all env variables start withs VITE_

import.meta.VITE_SOME

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.