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)


Login.tsx file

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

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.


 "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:


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({

PUBLIC_URL Reference Documentation

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