guide9 min readBy Aliniyaz Mamat · updated

How to use dotenv: Node, React, Next.js & more

How to use dotenv in one sentence: install it, load it before any code reads configuration, then read process.env.KEY. This guide shows exactly that for Node.js (four ways), React with Vite, Next.js, webpack, Python, Django, Rails, Laravel, Go and Docker, plus the load-order rules that decide which value wins.

Key takeaways

  • ✓Node.js 20.6+ needs no package: node --env-file=.env app.js. Otherwise import "dotenv/config" as the very first import.
  • ✓dotenv never overwrites a variable that's already set (shell, CI, host). Pass override: true only if you really want the file to win.
  • ✓Browser code never runs dotenv: Next.js and Vite inline NEXT_PUBLIC_ / VITE_ variables at build time.
  • ✓With dotenv.config({ path: [a, b] }) the first file wins; with node --env-file=a --env-file=b the last does.
  • ✓Production hosts set variables themselves; your .env is for local development.

Node.js: four ways to load .env

1. Built in: --env-file (Node 20.6+)

node --env-file=.env server.js
node --env-file=.env --env-file=.env.local server.js   # later file wins
node --env-file-if-exists=.env.local server.js          # Node 22.9+: no error if missing

Since Node 21.7 there's also process.loadEnvFile(".env") for loading from code. No variable expansion (${OTHER}) and no multi-file priority logic; for those, use the dotenv package.

2. dotenv/config: one import

// npm install dotenv
import "dotenv/config";      // ESM: must be the first import
// require("dotenv/config"); // CommonJS

import { db } from "./db.js"; // now sees process.env.DATABASE_URL

3. dotenv.config(): with options

import dotenv from "dotenv";

const result = dotenv.config({
  path: [".env.local", ".env"], // first file that defines a key wins
  quiet: true,                  // recent versions log a line on load
});
if (result.error) throw result.error;

4. dotenv-cli: for commands that don't load dotenv

package.json
{
  "scripts": {
    "migrate": "dotenv -e .env.local -- prisma migrate dev"
  }
}

Need ${OTHER_VAR} references inside .env? Add dotenv-expand: dotenvExpand.expand(dotenv.config()). Full Node.js template: Node.js .env generator.

React, Vite and webpack

# Vite: only VITE_* reaches client code
VITE_API_URL=https://api.example.com
# read with: import.meta.env.VITE_API_URL

# Create React App (deprecated): only REACT_APP_*
REACT_APP_API_URL=https://api.example.com
# read with: process.env.REACT_APP_API_URL

Both inline the values into the JavaScript bundle at build time, so they are public and changes need a rebuild. Raw webpack setups add dotenv-webpack (plugins: [new Dotenv()]) or pass selected keys through DefinePlugin. Details: NEXT_PUBLIC_ vs VITE_, React .env generator.

Next.js

Next.js loads env files itself, no import needed. Priority, highest first: .env.[mode].local → .env.local → .env.[mode] → .env, where mode is development, production or test (.env.local is skipped in tests). Real environment variables beat all files.

.env.local
DATABASE_URL=postgres://localhost/app          # server only
NEXT_PUBLIC_API_URL=https://api.example.com    # also in the browser bundle

More: NEXT_PUBLIC_ variables, Next.js .env generator, and for deployment Vercel environment variables.

Python and Django

# pip install python-dotenv
import os
from pathlib import Path
from dotenv import load_dotenv

load_dotenv(Path(__file__).resolve().parent / ".env")   # explicit path is safer than cwd
DATABASE_URL = os.environ["DATABASE_URL"]                  # KeyError if missing
DEBUG = os.getenv("DEBUG", "false").lower() in ("1", "true", "yes")

Django projects usually prefer django-environ (env.db("DATABASE_URL"), typed casting); FastAPI projects pydantic-settings. Templates: Django, Python.

Ruby on Rails, Laravel and Go

Gemfile
group :development, :test do
  gem "dotenv-rails"   # plain Ruby: gem "dotenv" + Dotenv.load
end
# read: ENV.fetch("DATABASE_URL")
config/database.php
// Laravel reads .env at boot (vlucas/phpdotenv). Call env() only in config files:
'database' => env('DB_DATABASE', 'forge'),
// app code: config('database.connections.mysql.database')
// go get github.com/joho/godotenv
import (
	"os"
	"github.com/joho/godotenv"
)

func main() {
	_ = godotenv.Load() // ignore "file not found" in production
	dbURL := os.Getenv("DATABASE_URL")
}

Laravel's php artisan config:cache stops reading .env, so env() outside config files returns null in production. Templates: Rails, Laravel, Go.

Docker and Docker Compose

compose.yaml
services:
  api:
    env_file: .env            # variables for the container
    environment:
      NODE_ENV: production    # beats the same key from env_file

docker run --env-file .env does the same for single containers (quotes are taken literally there). Convert a .env to Compose, Dockerfile or a Kubernetes Secret with the ENV to Docker converter.

Which value wins? Load-order rules

SituationWinner
variable set in shell/CI/host and in .envthe environment (dotenv, python-dotenv, Next.js, Vite, Compose)
same key twice in one filethe last line
node --env-file=a --env-file=bb
dotenv.config({ path: [a, b] })a
Next.js .env.local vs .env.env.local
Compose environment: vs env_file:environment:

To see the effective result of several files, stack them in the ENV merger. If something still doesn't load, go through how to fix .env errors.

Frequently asked questions

What does require('dotenv').config() actually do?

It reads .env from the current working directory (or the path you pass), parses each KEY=value line and copies the keys into process.env, skipping keys that are already set.

dotenv, dotenv/config or dotenv-cli: which one?

dotenv/config for apps (one import), dotenv.config() when you need options, dotenv-cli for npm scripts and tools that don't load dotenv themselves. On Node 20.6+, --env-file replaces all three for simple cases.

Does dotenv work in the browser?

No, it reads files from disk. Bundlers inline selected variables at build time instead: NEXT_PUBLIC_ in Next.js, VITE_ in Vite.

Why isn't my .env variable showing up?

dotenv ran after the code that reads it, the file is not in the working directory, a shell variable with the same name overrides it, or it's read in browser code without the public prefix. Checklist: how to fix .env errors.

Do I still need dotenv with Node 22?

Not for basic use: node --env-file=.env is built in. Keep dotenv for variable expansion, multiple files with first-wins priority, or older Node versions.

Related tools

Continue reading