Error: Unspecified process.env property when using dotenv and node.js

I'm encountering an issue with the dotenv package.

Here's the structure of my application folder:

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

Even though I have installed dotenv, the process.env variables are always undefined when I attempt to log them. Can someone assist me with this problem?

Content of password.env:

//password.env 
CLIENT_ID=xxxxxxxx

Content of 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 in advance for your help.

Answer №1

If you want to load a file different from the default .env using the dotenv package, you can specify the path as shown below:

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

For more information on the dotenv package, check out their official documentation:

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

Answer №2

Opting for import over require. -

You have the option to preload dotenv using -r (require). This way, you eliminate the need to manually require and load dotenv in your application code.

 $ node -r dotenv/config app.js

Answer №3

After dealing with a similar issue for some time, I discovered that placing the .env file at the topmost level of the directory resolves the problem effectively.

Although this post is dated, I hope it serves as a helpful reminder to prevent others from facing difficulties with such a basic task in the future.

Answer №4

Despite placing the .env file in the main directory, I was still encountering issues with console.log(process.env.myKey) showing as undefined. The solution that worked for me was directly specifying the path to the env file within the require configuration itself as shown below. (Located at the root of the file - so "./.env")

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

Answer №5

Here's a crucial reminder:

Make sure to place your .env file in the main directory, not within the /src folder

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue when utilizing TypeScript MongoDB Definitions (Unable to locate namespace)

I am currently working on implementing MongoDB typings that I installed using the following command: npm install @types/mongodb -D Now, I want to utilize these types within a function like this: export default async function insertOne(collection:any, da ...

Error: The function client.db is not recognized in MongoDB Atlas

I am attempting to establish a connection to MongoDB Atlas in Node.js using the client "mongodb": "^3.5.5" by following the instructions provided in this particular guide. A successful connection message of console.log('connected to db') is displ ...

There was an issue locating a declaration file for the module 'clarifai'

https://i.stack.imgur.com/PgfqO.jpg I recently encountered a problem after installing the Clarifai API for a face recognition project. Despite my efforts, I have been unable to find a solution. When I hover over "import clarifai," I receive the message: ...

Selenium htmlUnit with dynamic content failing to render properly

My current project involves creating Selenium tests for a particular website. Essentially, when a user navigates to the site, a CMS injects some dynamic elements (HTML + JS) onto the page. Everything works fine when running tests on the Firefox driver. H ...

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...

How can I extract data from a swiffy animation?

Suppose I am tracking the number of mouse clicks in Flash. To do this, I have utilized the following code: import flash.events.MouseEvent; plus.addEventListener(MouseEvent.CLICK,aaa) var i:int=0; function aaa(e:MouseEvent) { i++; var a:Number ...

Issue encountered while trying to run `npm install` on an angular-cli

I recently moved my angular-cli project with node modules to a new directory. Upon running npm install, I encountered the following warnings: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e2838c85978e8 ...

Transforming JSON data into a visually appealing pie chart using highcharts

I'm having trouble loading my JSON string output into a highcharts pie chart category. The chart is not displaying properly. Here is the JSON string I am working with: var json = {"{\"name\":\"BillToMobile\"}":{"y":2.35},"{\ ...

Error message stating 'compression is not defined' encountered while attempting to deploy a Node.js application on Heroku

Why is Heroku indicating that compression is undefined? Strangely, when I manually set process.env.NODE_ENV = 'production' and run the app with node server, everything works perfectly... Error log can be found here: https://gist.github.com/anony ...

Custom sample rate options in RecordRTC allow for the recording of silent audio tracks

I am currently working on implementing RecordRTC.js to capture audio from a microphone and then upload it to a server built with nancyfx. Initially, I am simply aiming to upload the audio stream and store it in a wav file for testing purposes. However, my ...

After the recent update, WebStorm has become unresponsive and is displaying an error related to

This morning, I updated my WebStorm and now my project is not running properly. It seems to be stuck on /usr/local/bin/node without executing any further. Has anyone else experienced this issue? Specifically, the problem lies with the green 'run node ...

When utilizing array.push() with ng-repeat, it appears that separate scopes are not generated for each item

I'm currently working on an Angular View that includes the following code snippet: <div ng-repeat="item in items track by $index"> <input ng-model="item.name"/> </div> Within the controller, I utilize a service to retrieve a Js ...

Is there a meteor server that supports per-request sessions?

I've implemented an authentication layer in my Meteor app, but I'm stuck on one particular detail. Unlike traditional apps with routes, I've integrated a hook into the connect middleware that throws an error for the "/" route if there's ...

Locate the package.json file while executing an npm script during the preinstall phase

Before installing a new npm package, it is essential to read the package.json. The Importance of Reading package.json When using npm for CSS components with individual versioning and possible interdependencies (without JavaScript), conflicts may arise. D ...

Interrupt the sequence of promises - prevent the subsequent 'then' function from running

I'm currently working on developing a registration system using Node/Express and I've been experimenting with Promises. However, I've encountered an error message while incorporating them: Error: (node:64725) UnhandledPromiseRejectionWa ...

Encountered an Unpredictable SyntaxError: Is this a Cross-Domain Problem?

I have been attempting to connect with the Indian Railway API using Ajax in order to retrieve data in JSON format. Below is the code I am using: <!DOCTYPE> <html> <head> <meta charset="UTF-8"> <script src="https://ajax.googleap ...

What happens when an AJAX request doesn't have a success field?

Is it possible to execute an ajax call without specifying a success function? $.ajax({ type: "POST", url: "/project/test/auto", data: data, // no success function defined here }); My reasoning for this is that I have PHP code that insert ...

Is there a way to efficiently fetch localStorage data upon launching a React application and seamlessly store it in Redux using the useEffect hook without experiencing any data loss issues?

Should I avoid mixing React hooks and mapStateToProps in my application and instead use Redux hooks like useSelector? In my React app, I have an array of 'friend' data stored in Redux. Using useEffect in one of my components, I am saving this da ...

Tips for closing the stdio pipes of child processes in node.js?

Looking to spawn a child process from node.js and monitor its stdout before closing the pipe to terminate the node process. Here's my base code snippet that is currently not ending the node process: const childProcess = require("child_process"); con ...

Using Selenium to stream audio directly from the web browser

For my current project, I am utilizing Selenium with Python. I have been exploring the possibility of recording or live streaming audio that is playing in the browser. My goal is to use Selenium to retrieve the audio and send it to my Python application fo ...