nad
nad

Reputation: 2870

Secret key in .env file doesn't work in NodeJS

I have a bunch of secret keys that I want to keep in .env file and reference it in my app.js

I installed dotenv

In my app.env file

ROOMID =abcxyz
BOTEMAIL [email protected]

In my app.js

require('dotenv').config();
var roomID = process.env.ROOMID
var botEmail = process.env.BOTEMAIL

When I run app.js that uses roomID to send a message, it can't write the message because it can't find the roomID

If instead I directly use

var roomID = 'abcxyz'
var botEmail = '[email protected]'

then the program works. What am I missing?

Upvotes: 2

Views: 3047

Answers (1)

Alex Baban
Alex Baban

Reputation: 11742

If you use

require('dotenv').config();

your file should have the name .env not app.env and should be located in the root directory of your project.

You can specify a custom path if your file containing environment variables is named or located differently.

require('dotenv').config({path: '/full/custom/path/to/your/env/vars'});

In your case if your file app.env is in the root of your app, then that would be:

require('dotenv').config({path: 'app.env'});

Also, if the same variable is defined in your actual system environment variables, then that value will be used instead of the one from .env file.


I hope this helps.

Upvotes: 2

Related Questions