Env Vars

Some variables in your app will vary between different computers where it is run on (your computer, your teammate's computer, your production server, etc.) Such variables include PORT numbers, database URLs, secret keys, and API keys. It is considered best practice to store these configuration variables in environment variables.

Dependencies

npm i dotenv
  • dotenv Reads variables defined in a .env file and puts them in the environment (process.env).

The .env File

To make working with environment variables during development easier, you write all your configuration variables in a .env file in the project root. Then require dotenv and call its .config method to read the .env file. This must be done as early as possible in your app.

.env

PORT=3000
DB_URL=postgresql://USER:PASSWORD@localhost:5432/scavenger_hunt
SESSION_SECRET=Sooper sekrit phrase

app.js

require('dotenv').config()

// ...

const PORT = process.env.PORT
const connectionString = process.env.DB_URL

const pool = new Pool({
  connectionString
})

// ...

Ignore the .env File

Your .env file will contain sensitive information you don't want anyone else to see so make sure you put it in .gitignore.

.gitignore

node_modules
.env

Last updated