Skip to content

Instantly share code, notes, and snippets.

@gnchrv
Last active December 19, 2019 23:12
Show Gist options
  • Save gnchrv/ffe7e9d9e34178e7e136ae30cdb275b6 to your computer and use it in GitHub Desktop.
Save gnchrv/ffe7e9d9e34178e7e136ae30cdb275b6 to your computer and use it in GitHub Desktop.
Configuration of .env-variables in Node.js

This is a custom setup that helps to set environment variables specified in an .env-file. This script utilizes dotenv module and allows to run it without specifying a path to the .env-file every time. (It's implied that this script is located in the same directory as the .env-file)

To use this module:

  1. Install dotenv package:
npm i -S dotenv
  1. Require this module in the beginning of a file and execute a function returned by this module:
require('./config.js')()

const express = require('express')
const app = express()

// etc.

Example of an .env-file:

# Variables that should not be seen in code
REMOTE_API_KEY=somekey
DATABASE_PASSWORD=thisismypassword
// Reqruire and execute this module in the beginning of every entry point of the application
const dotenv = require('dotenv')
let configured = false
module.exports = () => {
// Quit if it's been already configured
if (configured) return
// Otherwise configure and leave a note
dotenv.config({ path: '.env' })
configured = true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment