Dotenv not loading properly

I am trying to access some environment variables using process.envwhich were loaded 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 am trying to access the variable process.env:

(...)
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, undefinedand then crash with

TypeError: JwtStrategy requires a secret or key

Even if I move .envto src(the same directory as the server) and delete pathto config, it fails.

+4
source share
3 answers

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

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

.env - your file

+5
source

require('dotenv').config() nodejs.js, .

docs:

:.env

, , -.

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

+1

:

require('dotenv').config({ path: require('find-config')('.env') })

, .env .

, ckey .

.env .

# dotenv sample content
USER=sample@gmail.com
PASSWORD=iampassword123
API_KEY=1234567890

- js

const ck = require('ckey');

const userName = ck.USER;     // sample@gmail.com
const password = ck.PASSWORD; // iampassword123
const apiKey   = ck.API_KEY;  // 1234567890
0

Source: https://habr.com/ru/post/1669986/


All Articles