Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined process.env variable with dotenv and nodejs

I have a problem with the dotenv package.

My application folder:

 |_app_folder
      |_app.js
      |_password.env
      |_package.json

I've of course install dotenv, but when i tried to log a process.env variables, the result is always undefined, please can you help me ?

password.env :

//password.env 
CLIENT_ID=xxxxxxxx

app.js :

//app.js
const express = require('express');
const app = express();
const Twig = require("twig");

//Require dotenv
require('dotenv').config();

// Setting the Twig options
app.set("twig options", {
    allow_async: true, 
    strict_variables: false
});

app.get('/', function (req, res) {
  //Trying to log it
  console.log(process.env.CLIENT_ID);
  //
  res.render('index.twig', {
    date : new Date().toString()
  });
});

app.get('/instagram',function(req,res){
  // Building the URL
  let url = 'https://api.instagram.com/oauth/authorize/?client_id=';
  // Redirect to instagram for oauth 
  res.redirect(url);
})

app.listen(3000, function () {
  console.log('Running');
})

Thank you for your time.

like image 509
thomasA Avatar asked Aug 28 '18 18:08

thomasA


People also ask

Why is process env port undefined?

When trying to access process. env. PORT it'll return undefined if you've not setup that environment variable in the shell that you're trying to run your system. You can set the environment variable up before you run node app.

What is .env file in node JS?

The dotenv package for handling environment variables is the most popular option in the Node. js community. You can create an. env file in the application's root directory that contains key/value pairs defining the project's required environment variables.


3 Answers

By default the dotenv package does only load a file named .env if you want to load another file you need to specify the path

require("dotenv").config({ path: "path/to/file" })

Resources:

https://www.npmjs.com/package/dotenv

like image 194
Patrick Hollweck Avatar answered Oct 20 '22 00:10

Patrick Hollweck


When using import instead of require. -

You can use -r (require) to preload dotenv. You do not need to require and load dotenv in your application code.

 $ node -r dotenv/config app.js
like image 25
Gaurav Sharma Avatar answered Oct 19 '22 22:10

Gaurav Sharma


I was having somewhat the same problem for a while turns out you just have to put the .env file in the root of the directory (top-most level).

I know this post is old but I just want to make sure no one struggles with such a simple task again.

like image 45
curtis Arrisol Avatar answered Oct 19 '22 22:10

curtis Arrisol