dotenv file is not recognized by server nodejs - javascript

this is my first mern stack project ever and i'm trying to push it to github.
i am using mongoose so i had to hide the login and pwd of my account i looked it up and found the .env solution.
I created a dot env file
#.env file
Port=5000
CONNECTION_URL=mongodb+srv://+++++++++#cluster0.p5v9c.mongodb.net/++++++?retryWrites=true&w=majority
i ran npm i dot env
then i added import statement: import dotenv from 'dotenv';
and the problem seems to occur here,
i tried:
dotenv.config();, require('dotenv').config();, require ('dotenv/config');.
the code to of my index js if it helps to solve the solution :
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.set('useFindAndModify', false);
can anyone help me solve this up i would really appreciate it thank you ^^

After installing you do not need to import dotenv.
Remove the line:
import dotenv from 'dotenv';
Include dotenv with just:
require('dotenv').config()

Related

Node.Js MongoParseError URI malformed, cannot be parsed

When I run it on my local computer I don't get any problem, I encounter this error when I deploy it to Heroku. I don't fully understand the reason.
MongoParseError URI malformed, cannot be parsed
I just get this on Heroku. Also, my file on the server.js side is as follows.
const dotenv = require("dotenv");
dotenv.config({ path: "./.env" });
const app = require("./app");
const DB = process.env.DATABASE.replace(
"<PASSWORD>",
process.env.DATABASE_PASSWORD
);
console.log(DB);
mongoose
.connect(DB, {
auth: {
user: process.env.MONGO_DB_USER,
password: process.env.MONGO_DB_PASSWORD,
},
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
})
.then(() => console.log("DB connection successful!"));
"mongoose": "^5.13.14", "mongoose-intl": "^3.3.0", "dotenv":
"^16.0.3",
My .env file has MongoDB URLs and passwords. That's why I don't share. Works great locally too. but there are problems in deployment.
I had the same issue and it was caused by the fact that on heroku the node version was updated to 19.0.0.
To find out which version of node is being used on heroku, run heroku run 'node -e "console.log(process.versions)"'
The error is caused by mongoose version, maybe you are using an old one.
To solve this, try to update to mongoose 6.7.2 and you should be fine.
If you sure your environment variables are same, it may be related to ip.
Try adding 0.0.0.0/0 IP address in Atlas Network Access. If you already have this IP, then delete and add it again. After that restart all dynos in Heroku. (inside dropdown menu at top right)
check your server dotenv value.
In a cloud environment the .env file may be different.
can you check local process.env and Heroku's process.env?
It seems that there is an error in your mongoDB URI
For now i don't know what your URI is which is .env file but i can suggest you a few things
1- Firstly you need to replace the first two lines of your code with this one
require('dotenv').config();
2- In your .env file you need to create a variable named
MONGODB_URI=mongodb+srv://[username:password#]host[/[database][?options]]
whatever your password and username is just fill in that here in URI
Finally you need to change the connection string and your file should look like this
require('dotenv').config();
const app = require("./app");
mongoose
.connect(process.env.MONGODB_URI)
.then(() => {
console.log("Connection Successfull");
})
.catch((error) => {
console.log("Connection Unsuccessfull");
});

Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"

Invalid scheme, expected connection string to start with "mongodb://" or "mongodb+srv://"
I am using MongoDB atlas
Index.js
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import postRoutes from "./Routes/posts.js";
import dotenv from "dotenv";
const app = express();
dotenv.config();
app.use(bodyParser.json({ limit: "50mb", extended: true }));
app.use(bodyParser.urlencoded({ limit: "50mb", extended: true }));
app.use(cors());
app.use("/posts", postRoutes);
const PORT = process.env.PORT || 4000;
mongoose
.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
app.listen(PORT, console.log(Server is running on port ${PORT}));
})
.catch((err) => console.log(err.message));
.env file
CONNECTION_URL =
"mongodb+srv://<UserName>:<Password>#cluster0.v5qzigz.mongodb.net/?retryWrites=true&w=majority";
PORT = 4000;
it works fine if i do not use .env File. Process.env.CONNECTION_URL is not working ?
If the <Username> or <Password> includes those following characters, simply replace them.
: / ? # [ ] #
I also had the exact same problem while following a course. Then I remembered on my last project it worked. So I went to look at the code on my last project then a solution popped up that helped me and could probably help you.
Please try to delete your dotenv file and make it again. Then try to make the connection variable(remove the strings) again and make show your code editor doesn't highlight with any color. (it must be plane light black the whole variable) then try to save it and see if it works.
This worked for me I hope it helps you
The problem is most likely that the variable is not formatted correctly in .env.
Remove the spaces, the quotes, and the semi-colon at the end.
This
CONNECTION_URL =
"mongodb+srv://<UserName>:<Password>#cluster0.v5qzigz.mongodb.net/?retryWrites=true&w=majority";
Becomes this
CONNECTION_URL=mongodb+srv://<UserName>:<Password>#cluster0.v5qzigz.mongodb.net/?retryWrites=true&w=majority
Then the connection should work
mongoose.connect(process.env.CONNECTION_URL).then(()=>{
console.log('Atlas DB Connected...' )
}).catch(err => {
console.log('Atlas DB connection failed...', err )
})

using dotenv module in nodejs and typescript

i create a file by this name .env :
DATABASE_URL='mongodb://localhost:27017/Fimstan'
SERVER_PORT=3000
now i want to use that in the app.ts for using the SERVER_PORT .
import * as dotenv from 'dotenv';
dotenv.config();
app.listen(process.env.SERVER_PORT, () => {
console.log(`Server Run On Port ${process.env.SERVER_PORT}`);
});
but it show me this message in terminal : Server Run On Port undefined
now whats the problem ? how can i use the .env content in my project ???
import express, { Request, Response, NextFunction } from 'express';
import * as dotenv from 'dotenv';
import http from 'http';
import Logger from './core/logger/logger';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import passport from 'passport';
import cors from 'cors';
import redisClient from 'redis';
import path from 'path';
import configuration from './config/index';
import cookieParser from 'cookie-parser';
process.on('uncaughtException', (e) => {
Logger.error(e);
});
dotenv.config();
const app: express.Application = express();
app.listen(process.env.SERVER_PORT, () => {
console.log(`Server Run On Port ${process.env.SERVER_PORT}`);
});
app.get('/', (req, res, next) => {
console.log('Hello')
})
mongoose.Promise = global.Promise;
mongoose.connect(configuration.databaseConfig.url, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser("SchoolManagerSecretKey"));
First, you need to make sure that you set the important parts correctly for this to work.
That is why I will ignore the rest of your imports and app logic. Try to test the solution I described separately to check if this solves your problem.
Make sure that on your root project folder you have the package.json file and .env file.
In the terminal in the path to the root project folder write 'npm i dotenv' (note: it already containing the definitions you required in Typescript).
Now to the files:
// root/.env
SERVER_PORT=3000
// root/app.ts
import dotenv from 'dotenv';
dotenv.config();
console.log(`Server Run On Port ${process.env.SERVER_PORT}`);
Also, note that you get the type (string | undefined) when doing an assignment from process.env.variableName.
(I am assuming that you are working with the latest versions of node, dotenv and typescript but I don't think there is much if any a difference in older versions).

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

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