Install and Set Up Mongoose .env issues

Okay I am a bit lost.

If I define MONGO_URI in the myApp.js file, it works.

But if I reference it from my .env file, it doesn’t work.

Am I naming my .env file correctly? Or do I need to include it in the document? What why do I have to call “process.env” vs “.env”?

In the .env file, try surrounding the uri with single quotes.

1 Like

.env file is a private file where you would keep secrets, like mongo passwords and API keys. This file should not go to any public places, like GitHub repository for example.

process.env is a NodeJS command for adding environment variables and adding secret in potentially public file make no sense, what you need is read contents of .env file, parse keys and values and add each key-value pair with process.env. You can do that, or you can just use package that does the same:

FYI - Glitch installs dotenv globally so the user does not explicitly have to install with their package.json file.

But still needs to require('dotenv').config(), right?

Nope. Somehow it just “works”. I have not looked at the source code, but I will at some point. It is now open source.

@snigo Actually, I just assumed dotenv was installed globally. After testing to see if it is installed with the following, and I get “Can’t load dotenv” in the console. However, you can reference process.env and it will pull from the .env files somehow.

try {
    var foo = require("dotenv");
catch (e) {
    if (e instanceof Error && e.code === "MODULE_NOT_FOUND")
        console.log("Can't load dotenv");
        throw e;

That was it! Thanks!