Using .env file in a NodeJS project

Anh-Thi Dinh

Setting up

For a simple nodejs project,
1npm init -y
2npm i dotenv
3
4# Create .env in this project
5# MAKE SURE IGNORE IT IN GIT !!!

Usage in a Node.js

1// At the top of the app
2require('dotenv').config()
3
4// Use
5const db = require('db')
6db.connect({
7  host: process.env.DB_HOST,
8  username: process.env.DB_USER,
9  password: process.env.DB_PASS
10})

Use with js file

Use with a simple .js file? Using command line!
1node -r dotenv/config your_script.js
2
3# Custom path
4node -r dotenv/config your_script.js dotenv_config_path=/custom/path/to/.env
5
6# Single variable
7DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js

Use it in Github?

1# In Github Action
2<https://github.com/dinhanhthi/><your-repo>/settings/secrets/actions
3
4# In Github Codespaces
5<https://github.com/dinhanhthi/><your-repo>/settings/secrets/codespaces
6
7# In Dependabot
8<https://github.com/dinhanhthi/><your-repo>/settings/secrets/dependabot
An example of using Github Action (key SECRET_TOKEN is already defined in /settings/...),
1# Use a GitHub Actions secret variable in a bash shell
2- name: Step 2 - GitHub Action if statement (true)
3  env:
4    WHO_TO_TRUST: ${{ secrets.SECRET_TOKEN }}
5  if:  env.WHO_TO_TRUST == 'TrustNo1'
6  run: echo "I know what the secret token is!"
Loading comments...