Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node dotenv won't work with pm2

Tags:

I have an application where locally (without pm2) all the environment variables in the .env file work just fine using dotenv.

But on the server where I'm using pm2 to run the app, the environment variables remain undefined.

The pm2 commands I'm using to run the app on server are:

pm2 start myapp/app.js pm2 startup pm2 save 
like image 520
m-ketan Avatar asked Jun 04 '18 22:06

m-ketan


People also ask

Should dotenv be a dev dependency?

tl;dr - Yes, dotenv is really recommended for development only, but you can use it for production as well, if you are careful and understand the implications. To understand why dotenv is recommended fo development only, let's take a look at the things people generally put into their .


1 Answers

dotenv will read .env file located in the current directory.

When you call pm2 start myapp/app.js it won't search for myapp/.env.

.env // It will try to load this, which doesn't exist myapp/    app.js 

So you have two solutions

use path option:

const path = require('path');  require('dotenv').config({ path: path.join(__dirname, '.env') }); 

Or call your script from inside myapp/

pm2 start app.js 
like image 73
Marcos Casagrande Avatar answered Sep 22 '22 17:09

Marcos Casagrande