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

前端 未结 30 1146

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:54

    My code structure using is as shown below

    -.env
    -app.js
    -build
    -src
       |-modules
            |-users
                |-controller
                      |-userController.js
    

    I have required .env at the top of my app.js

    require('dotenv').config();
    import express = require('express');
    import bodyParser from 'body-parser';
    import mongoose = require('mongoose');
    

    The process.env.PORT works in my app.listen function. However, on my userController file not sure how this is happening but my problem was I was getting the secretKey value and type as string when I checked using console.log() but getting undefined when trying it on jwt.sign() e.g.

    console.log('Type: '+ process.env.ACCESS_TOKEN_SECRET)
    console.log(process.env.ACCESS_TOKEN_SECRET)
    

    Result:

    string
    secret
    

    jwt.sign giving error

    let accessToken = jwt.sign(userObj, process.env.ACCESS_TOKEN_SECRET); //not working 
    

    Error was

        Argument of type 'string | undefined' is not assignable to parameter of type 'Secret'.
      Type 'undefined' is not assignable to type 'Secret'.
    

    My Solution: After reading the documentation. I required the env again in my file( which I probably should have in the first place ) and saved it to variable 'environment'

    let environment = require('dotenv').config();
    

    console logging environment this gives:

    {
    parsed: {
        DB_HOST: 'localhost',
        DB_USER: 'root',
        DB_PASS: 'pass',
        PORT: '3000',
        ACCESS_TOKEN_SECRET: 'secretKey',
      }
    }
    

    Using it on jwt.sign not works

    let accessToken = jwt.sign(userObj, environment.parsed.ACCESS_TOKEN_SECRET);
    

    Hope this helps, I was stuck on it for hours. Please feel free to add anything to my answer which may help explain more on this.

提交回复
热议问题