Recommand · May 26, 2021 0

Setting PUBLIC-URL in .env file React application

Hi I am new in react application. I want to set Public_URL in .env file .

.env file (I set my url link)

PUBLIC_URL="http://localhost:8000/api";

Login.tsx file

const response = await fetch("/login", {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'include',
            body: JSON.stringify({
                userName,
                password
            })
            
        });

When i start the application, My application should be work fine. But In my Login page I submit the Login button My Url call to http://localhost:3000/login. But I need to set http://localhost:8000/api . I don’t know how to set it. Please send the correct example.

Package.json

 "scripts": {
    "start": "env-cmd -f .env react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

You can set in .env file another variable for your endpoint, for example:

REACT_APP_API_ENDPOINT=http://localhost:8000/api

PUBLIC_URL is already used as base url to React get the dependencies of your application.

In your component you can get the environment variable this way:

const { REACT_APP_API_ENDPOINT } = process.env;

const response = await fetch(`${REACT_APP_API_ENDPOINT}/login`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  credentials: "include",
  body: JSON.stringify({
    userName,
    password,
  }),
});

PUBLIC_URL Reference Documentation

https://create-react-app.dev/docs/using-the-public-folder/

It must be used for external web resource like Icon, Image, CSS. It is meant for internal reference to current web page link.