Undefined process.env variable with dotenv and nodejs - javascript

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.

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

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.

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

Even though I put the .env file in the root folder, still console.log(process.env.myKey) is undefined. The fix worked for me is I put the path to the env file in the require config itself like below. (It's in the root of the file - so "./.env)
require("dotenv").config({path:"./.env"})

Another important note:
Place your .env file in the root folder, not in /src

Related

How to assign variables in .env file?

Q1.
I have a .env file in my ReactJS app like this:
API_1_ROOT='http://my-api-1.com'
API_2_ROOT='http://my-api-2.com'
BASE_API=API_1_ROOT // This doesn't work as expected
I want to assign one of these api roots to my base api root; I tried doing this in my .env file but it doesn't work as expected.
How can I do this in my .env file?
Q2.
Also, I am not able to destructure multiple items from process.env like this:
const { API_1_ROOT, API_2_ROOT } = process.env;
When I'm doing this, I'm getting the following error:
Uncaught ReferenceError: process is not defined
I have to do this to get both variables:
const { API_1_ROOT } = process.env;
const { API_2_ROOT } = process.env;
npm install dotenv --save
Next add the following line to your app.
require('dotenv').config()
Then create a .env file at the root directory of your application and add the variables to it.
.env
// contents of .env
REACT_APP_API_1_ROOT = 'my-secret-api-key'
REACT_APP_API_2_ROOT = 'my-secret-api-key'
config.js
require('dotenv').config()
const config = {
api1: process.env.REACT_APP_API_1_ROOT,
api2: process.env.REACT_APP_API_2_ROOT,
}
export default config

Not able to access dotnev variables

I have added a .env file in my nodeJs application and post that added below line in my app.js
require('dotenv').config();
I still cannot access the environment variables. What's is missing here?
.env file content
PORT: 3000
SPACE:"dev"
Password: "ABC"
and I am trying to access it using
process.env.PORT
Which is coming as 'undefined'
Update app.js
const express = require('express');
const app = express();
const cors = require('cors')
const path = require('path');
require('dotenv').config();')
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
app.use(express.json());
console.log(process.env.PORT)
app.listen(process.env.PORT || 3000);
module.exports = app;
.env files should have params as:
SPACE=dev
Password=ABC
The examples are mentioned on the github repo.
Keep your .env file in the same path of your app.js(server.js/index.js or main.js whatever you name to your root file).
.env file
PORT=3000
SPACE=DEV
PASSWORD=ABC
app.js file
require('dotenv').config()
console.log(process.env.PORT)
console.log(process.env.SPACE)
console.log(process.env.PASSWORD)
file-path
/my-app
app.js
.env
you have to specify the path where your .env file is, like this
require('dotenv').config({path: __dirname + '/../.env'});

Mongoose .env returning undefined

I am setting up my database connection using a MEVN stack but I am getting the following error;
The `uri` parameter to `openUri()` must be a string, got "undefined"
If I try console log process.env.DATABASE_URL it just returns undefined. What have I done wrong here's my code;
index.js
import dotenv from 'dotenv';
import Express from 'express';
import Mongoose from 'mongoose';
dotenv.config();
const app = Express();
Mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true });
app.listen(3000, () => {
// console.log(process.env.DATABASE_URL);
console.log('server started on port 3000');
});
.env
DATABASE_URL="mongodb+srv://reece:<password>#mevn-tutorial-cluster-egjs6.mongodb.net/auth?retryWrites=true&w=majority"
I removed my password for obvious reasons
You have to create a .env file in the root dir of your application.
in the .env file you should have key value separate by equal sign.
As example:
secret=foo
DATABASE_URL=bar:pwd#localhost.com
As the documentation states:
https://www.npmjs.com/package/dotenv
You have not used template literals for mongoose connections.
Try this:
Mongoose.connect(${process.env.DATABASE_URL}, { useNewUrlParser: true });
to get actual .env variable to your Javascript snippet.
I made this mistake, and you shouldn't do it either.
Make sure your.env file is in the root. Check the path of .env before proceeding ahead.
npm install dotenv
require("dotenv").config(); //Keep this at top of your file
In .env file, add
ADMIN_ID="mongoose://******************" //YOUR URL ADDRESS WITH PASSWORD
In app.js file,
mongoose.connect(process.env.ADMIN_ID);
It worked for me.
dotenv.config({ path: "config.env" });
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
})
use path. it'll work

NodeJS environment variables undefined

I'm trying to create some envrioment variables but when I create the file and run the server the seem to be undefined. I'm using nodemon. I have restarted my server and no luck.
UPDATED
.env
MONGO_ATLAS_PW = "xxxx";
JWT_KEY = "secret_this_should_be_longer";
package.json
...
"scripts": {
...
"start:server": "nodemon ./server/server.js"
}
app.js
require('dotenv').config();
...
console.log(process.env.JWT_KEY); //undefined
I believe the nodemon.json file is only for setting nodemon specific configuration. If you look at the nodemon docs for a sample nodemon.json file, the only env variable they mention setting is NODE_ENV.
Have you considered putting these environment variables for your app in a .env file instead? There is a package called dotenv that is helpful for managing env variables in Node.
First, install dotenv using the command npm install dotenv
Then, create a file called .env in the root directory with the following:
MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret_this_should_be_longer
Finally, inside your app.js file after your imports add the following line:
require('dotenv').config()
I believe you're referring to the dotenv package. To configure it, first create a file called .env with your keys and values stored like so:
MONGO_ATLAS_PW=xxxxx
JWT_KEY=secret_this_should_be_longer
Then, in your server.js, add this near the top:
require("dotenv").config();
Then the process.env variable will be an object containing the values in .env.
This needed to be in the root directory of my project.
nodemon.json
{
"env": {
"MONGO_ATLAS_PW": "xxxx",
"JWT_KEY": "secret_this_should_be_longer"
}
}
The env variable do not contain the trailing white spaces and also remove the quotes
MONGO_ATLAS_PW = "xxxx";
JWT_KEY = "secret_this_should_be_longer";
to
MONGO_ATLAS_PW=xxxx
JWT_KEY=secret_this_should_be_longer
and restart the server
or you can also try using the nodemon.json - create a new file called nodemon.json in your root directory
{
"env": {
"MONGO_ATLAS_PW" : "xxxx",
"JWT_KEY" : "secret_this_should_be_longer"
}
}
and restart the server
for accessing the variable
process.env.MONGO_ATLAS_PW
process.env.JWT_KEY

Custom module express js:Cannot find module name error when modules folder in root directory

Folder structure of my express js app look like this
I am trying to load a modules folder which is located in root directory
routes/users.js
var express = require('express');
var router = express.Router();
var md=require('./modules');
/* GET users listing. */
router.get('/',function(req, res, next) {
//res.send('respond with a resource');
console.log('test');
res.status(200).json({ error: 'message' });
});
module.exports = router;
But i am getting a module not found error:
Cannot find module './modules'
Note:
If modules folder is in node_modules folder require works fine,but getting module name error if its in project root directory,
also an index.js file is present in modules folder
Module resolution in NodeJS is relative to the directory of your dependent module when your resolution starts with ..
In other words :
var module = require('../modules'); // Since your file is in `./routes/index`
// and `module` is in `./modules/index`
If you don't supply . in front of the required module, then NodeJS will look for that module in node_modules directory.
Excerpt from the documentation, which is self explanatory.
require(X) from module at path Y
1. If X is a core module,
a. return the core module
b. STOP
2. If X begins with './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
So in your case when you require('./modules'). NodeJS looks for it in the current directory ./routes, then since it can't find it, goes to look at it in node_modules.
Instead of './modules' you can try require('../modules')

Categories