Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dotenv not loading properly

I am trying to access some environment variables using process.env that were loaded by dotenv.

My folder structure :

.env
src
-- - server.js

My server.js configuration :

(...)
import auth from './middleware/auth'
import dotenv from 'dotenv'
dotenv.load({
    path: '../',
    silent: process.env.NODE_ENV === 'production'
})
auth()
// Instantiate app
const app = express();

The file where I try to access process.env variable :

(...)
module.exports = function() {
        console.log("env", process.env.MONGODB_URI)
        var options = {};
        options.jwtFromRequest = ExtractJwt.fromAuthHeader()
        options.secretOrKey = process.env.JWT_SECRET

Which logs env, undefined, and then crashes with

TypeError: JwtStrategy requires a secret or key

Even if I move .env into src (same directory as server) and remove path in config, it fails.

like image 483
softcode Avatar asked Feb 16 '17 20:02

softcode


People also ask

How do you preload dotenv?

Preload. You can use the --require ( -r ) command line option to preload dotenv. By doing this, you do not need to require and load dotenv in your application code. This is the preferred approach when using import instead of require .

How do I set the dotenv path?

You can need the path of the . env file relative to the current working directory from where the application was launched. You can create this path like this: const path = require('path') require('dotenv').

How do you initialize a dotenv?

To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv'). config() .

Should .env files be committed?

env file should be committed to version control. The trouble is that blindly committing it creates a huge security risk. Here I discuss a few pointers on how to do so in a safe manner.


2 Answers

It appears that when you specify the path, you need to make it full:

require('dotenv').config({path: __dirname + '/../.env'});

.env being your file

like image 171
yBrodsky Avatar answered Sep 21 '22 16:09

yBrodsky


Try this; this should work.

import {} from 'dotenv/config'
import somethingElse from 'somethingElse'
...
[the rest of your code]

This works because of how ES6 modules imports modules.

If you want to dig into more. Please refer this. https://hacks.mozilla.org/2015/08/es6-in-depth-modules/

As a summary :

When you run a module containing an import declaration, the modules it imports are loaded first, then each module body is executed in a depth-first traversal of the dependency graph, avoiding cycles by skipping anything already executed.

Hope this will help someone.

like image 31
Chamika Avatar answered Sep 21 '22 16:09

Chamika