.env file not working even though i required it - javascript

I required .env in the first line of my server.js file and as well in the file that I'm using process.env.SENDGRID_API_KEY.
It seems that the variable in the .env file is not recognized, the text is not colored.
when I run the program I get "API key does not start with "SG."", but it does.
controller.js
require("dotenv").config();
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
server.js
require('dotenv').config();
const mongoose = require ('mongoose');
const express = require('express');
...
.env file
SENDGRID_API_KEY = 'SG.theRestOfTheAPIKey'

Try removing double quotes and the spaces between the variable definition in the .env file. It might be the issue:
SENDGRID_API_KEY=SG.theRestOfTheAPIKey

Related

How dotenv Package Work With pg.Pool in NodeJS

I've read some code that uses the dotenv package to create configurations.
When I read a file that contains PostgreSQL code for Pool, the code looks like this:
const pg = require('pg')
const { Pool } = pg
// This pool was created without completing the pool connection configuration. 
const pool = new Pool()
However, I see that this pool configuration is written in the.env file. 
#POOL CONFIGURATIONS
PGUSER=username
PGPASSWORD=password
PGHOST=localhost
PGDATABASE=databasename
PGPORT=5432
and .env file is called once in main file :
// main file
require('dotenv').config()
const express = require('express')
// below is the server
Why is a pool created without passing any configuration objects as arguments?
How does it work in the background?
I still can't figure this out clearly.
I've tried searching for this behavior, but I haven't found it yet.
When you run
require('dotenv').config()
that sets everything in your .env file to be on process.env.*.
For example, you say PGUSER=username, so now process.env.PGUSER === "username"
pg.Pool seems to go with those environment variables by default

Connecting to MongoDB database

I am trying to connect to a MongoDB database.I have followed all the steps here https://youtu.be/EcJERV3IiLM but am getting an error.
The index.js file looks like this,
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, async function(err,client){
const db = client.db()
const results = await db.collection("student").find().toArray()
console.log(results)
The error I get is,
mongodb.connect is not a function
So it seems to be reading as far line 5:9 which is mongodb.connect in index.js and just stops.
I put this file index.js beside the .env file and beside that .gitignore which contains the the .env file. The .env file has the code which I copied from the Mongodb AtlSAS Cloud Service.
I also created a user and and autogenerated and saved a password. Both of which I placed in the string. And I put in the string the name of the database name "blah" The table/document is called "student". That's in the index.js code above. So the database name and the document name are blah.student.
I documented what I tried here, http://www.shanegibney.com/shanegibney/mongodb-setup/
The tutorial video is here, https://youtu.be/EcJERV3IiLM
I am on Ubuntu Linux.
I am currently running index.js in the terminal in a directory called mongostack, with
node index.js
but should I use,
nodemon index.js
And for this should I install nodemon and how do I do that?
Do I need to download it first and if so where do I get it?
I think you need to get MongoClient. Try changing:
const mongodb = require('mongodb')
to:
const mongodb = require('mongodb').MongoClient;
You have to create a MongoClient see https://www.mongodb.com/docs/drivers/node/current/quick-start/
const { MongoClient } = require("mongodb");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
async function run() {
await client.connect();
const db = client.db("yourdb")
const results = await db.collection("student").find().toArray()
console.log(results)
}
run();

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'});

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.
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

Categories