← docs

How-to: Use dotenv with Express

Let's start by generating a hello world express app.

1

Install Express

Open terminal, create your project, and install express with npm.

mkdir hello-world
cd hello-world
npm install express --save
2

Code your express app

Create an index.js with the following code.

// index.js
const express = require('express')
const app = express()

app.get('/', function (req, res) {
  res.send('Hello World')
})

app.listen(3000, function () {
  console.log("Visit http://localhost:3000")
})

3

Run your app

Your app will run at http://localhost:3000, saying 'Hello World'.

node index.js
4

Create .env file

Create a .env file with the following contents.

# development .env
HELLO_MESSAGE="Good morning Love"

FYI: In Unix-like operating systems, any file or folder that starts with a dot character is treated as hidden by default.

5

Install dotenv

Install dotenv with npm.

npm install dotenv --save
6

Require dotenv in your code

Next, as early as possible in your application, import and configure dotenv.

// index.js
require('dotenv').config()
const express = require('express')
...

7

Insert HELLO_MESSAGE

Replace the Hello World string with your HELLO_MESSAGE environment variable.

dotenv loads all values from .env into Node's process.env1 property.

// index.js
...

app.get('/', function (req, res) {
  res.send(process.env.HELLO_MESSAGE)
})

...
8

Re-run your app

If still running, first stop the current running server (ctrl + c) and then re-run the server.

node index.js
9

Visit localhost:3000

Visit http://localhost:3000. Does your app now say 'Good morning Love'? Congratulations 🎉.


You're ready for the next step(s).