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.
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 .
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').
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() .
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.
It appears that when you specify the path, you need to make it full:
require('dotenv').config({path: __dirname + '/../.env'});
.env being your file
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With