How do I setup the dotenv file in Node.js?

前端 未结 30 1153

I am trying to use the dotenv NPM package and it is not working for me. I have a file config/config.js with the following content:



        
30条回答
  •  轮回少年
    2020-12-07 14:58

    If you are facing this problem it could be that the environment variable(s) is added/loaded after the file that requires the specific variable

    const express = require('express');
    
    const app = express();
    const mongoose = require('mongoose');
    const dotenv = require('dotenv');
    const morgan = require('morgan');
    
    const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get undefined)
    
    dotenv.config();
    

    in the above case, you will get undefined for the process.env.JWT_SECRET

    So the solution is that you put dotenv.config() before const passport = require('passport');

    const express = require('express');
    
    const app = express();
    const mongoose = require('mongoose');
    const dotenv = require('dotenv');
    const morgan = require('morgan');
    dotenv.config();   
    const passport = require('passport'); //you want to use process.env.JWT_SECRET (you will get the value for the enviroment variable)
    

提交回复
热议问题