Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Kavin Desi Valli
Kavin Desi Valli

Posted on • Originally published atlivecode247.com on

Local NodeJS Environment Variables

TheDotEnv is an NPM package which allows you to load local NodeJS Environment Variables in your project. It is based onThe Twelve-Factor App Methodology - Storing configuration in environment separate from code.

Installation

The installation is as easy as any other NPM Package

npm install dotenv# YARNyarn add dotenv
Enter fullscreen modeExit fullscreen mode

Setup

Create a.env file in your root directory. Add any env vars you want in that file. For eg.

DB_HOST=localhostDB_PORT=3306DB_USER=rootDB_PASSWORD=password
Enter fullscreen modeExit fullscreen mode

Load the variables

Now in your starting JS file (which you run usingnode <filename>.js) add the following line of code

require('dotenv').config()
Enter fullscreen modeExit fullscreen mode

What this does is, it imports thedotenv module using the CommonJS syntax and then calls theconfig function on it. This loads up the dotenv variables in the.env file created earlier. You can also pass an object as an argument into it which you can findhere

Use the variables

You can use the variables inside that file now like any other env variable using the Global Objectprocess and the objectenv inside it in the following way:

console.log(process.env.DB_HOST)
Enter fullscreen modeExit fullscreen mode

Note that you can use the env variables inside the .env file only after calling the config function in the dotenv module. So the above line of code needs to come after therequire('dotenv').config() function.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a full stack developer. I know Django, Node JS, Express, React JS, PostgreSQL, Mongo DB, SQlite
  • Location
    New Delhi
  • Education
    Delhi Public School, R.K. Puram
  • Work
    Co-Founder at Tricycle
  • Joined

More fromKavin Desi Valli

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp