You see some files prefixed with .env
(e.g. .env.local
, .env.production
, .env.example
, .etc.). These are “environment” variables, and are just like the environment variables you can manually set in your terminal (e.g. variable1=hi
). The difference is that your program set environment variables from these files during its runtime so that they won’t persist to your computer.
The main purpose of .env
files are to securely store data that your program needs, and they are accessible as environment variables. Say you needed to store the password to your database somewhere, but your repository is shared publicly on Github. .env
files help you accomplish this since they are ignored in .gitignore
and thus won’t be shared publicly.
.env
filesTo set environment variables, create a .env
file in the root folder of your environment. For example, you’d create the .env
in client/
and server/
folders in the mern-boilerplate.
You can create variables like so
key=value
SECRET_KEY=mySeCreTkEy
DATABASE_URI=database-uri:27017
It is conventional to name the variable in ALL CAPS. Moreover there are NO spaces; each environment variable definition is one string. For multiple environment variables, make sure to put each one on a separate line.
.env.example
In some cases, you’d see a .env.example
file. They serve as an example for your .env
and define what keys you need. Simply create a .env
and copy-paste everything from .env.example
.
NODE_ENV=development
PORT=8080
MONGO_URI=mongodb://127.0.0.1:27017/mern-boilerplate
CLIENT_URL=http://localhost:3000
SESSION_SECRET=
JWT_SECRET=
REFRESH_TOKEN_SECRET=
SESSION_EXPIRY=15m
REFRESH_TOKEN_EXPIRY=30d
In the mern-boilerplate, this is the .env.example
under server/
. There are some variables already defined (e.g. NODE_ENV
, PORT
, etc.), but there are some that don’t have values (e.g. SESSION_SECRET
, JWT_SECRET
, and REFRESH_TOKEN_SECRET
). After copy-pasting, you’d have to manually set these values. For the most part, environment variables in .env.example
are used for local development, so they’re fine to be explicitly defined.