Question

How do I properly set up and manage environment variables for my React application?

I've created three environment files for my Next.js project:.env.local ,.env.dev and .env.prod Each file contains similar environment variables for different stages (local, development, and production). for exemple :

HOST=https://localhost:7142/ 
NEXT_PUBLIC_Employees_API_URL = $HOST/api/Employee

I've added npm scripts to package.json to use these environment files:

 "scripts": {
  "dev": "next dev",
  "build": "next build",
  "start": "next start",
  "start:local": "env-cmd -f .env.local npm run dev",
  "build:local": "env-cmd -f .env.local npm run build",
  "start:dev": "env-cmd -f .env.development npm run dev",
  "build:dev": "env-cmd -f .env.development npm run build",
  "start:prod": "env-cmd -f .env.production npm run start",
  "build:prod": "env-cmd -f .env.production npm run build"
}

When I try to run these scripts, I expect to use npm run start:local for the local environment, npm run start:dev for the development environment, and npm run start:prod for the production environment. However, this setup isn't working as intended.

foor exemple when i tape npm run start:local it loads .env.development and .env.local

but when i tape http://localhost:7142 it shows nothing ERR_EMPTY_RESPONSE despite when tapping npm run dev it works with the env development Could you help me understand why these scripts are not working and how to correct them?

 3  33  3
1 Jan 1970

Solution

 2

Next.js will load .env.development to the environment by default when running npm run dev (this same behavior applies for npm run start with .env.production). What you seem to be doing is loading your own file, .env.local, on top of it.

As there does not seem to be a way to prevent this behavior, your only solution might be using a different file naming convention than that of Next.js. However, you should note the Next.js will always load the base .env file as a fallback when the file specific to the environment is missing.

2024-07-05
Kinan Dira