How to use .env with ES6 module with node js and express application?

Viewed 2018

I need your help on how I can use .env file on this application. here is my problem: I am building an app using ES6 module in my node express app. I am facing a problem while storing my variable in .env file, both these two ways below are giving this error : MongooseError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string. did not connect. But when I only use the plain string connect is working, that means that I am not using the dotenv file correctly:

1-

import {} from "dotenv/config.js";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";

const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
    {
      useCreateIndex: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })

app.listen(port,()=>console.log(`server on ${port}`) 

2-

import dotenv from "dotenv";
import express from "express";
import mongoose from "mongoose";
import cors from "cors";

dotenv.config();

const app=express()
...
//DB config
mongoose.connect(process.env.CONNECTION_URL,
    {
      useCreateIndex: true,
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })

app.listen(port,()=>console.log(`server on ${port}`)
4 Answers

Here is how to use it as ES6 module

import * as dotenv from 'dotenv';
dotenv.config();

Path is default to ./root/.

To add path to current directory (Dir), we need this code inside of the file that we want all variables to be imported

import dotenv from 'dotenv'
import path from 'path'

import {fileURLToPath} from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config({ path: path.join(__dirname, '.env') });
// const express = require('express')
import express from 'express';

server.js and .env can should be in the same directory if you don't manipulate the path.join(__dirname.

You can reach the variables process.env.myvariable. Just be sure it works and print all variables: console.log(process.env)

Thanks

If you don't need the return value from the dotenv.config() function, you can use this pattern to execute the config function as a side-effect of the import:

import 'dotenv/config';

I recommend this syntax because it improves compatibility with Typescript compilers that are strict about the ESM spec (i.e. SWC) and also provides better compatibility with code-formatting rules that want to re-order your import statements.

You are right, you are not fetching the env variables.

I'll tell you how I do it. Just create a .env file with your variables.

Then in your app.js:

const dotenv = require('dotenv');
dotenv.config();

And to use the variable uri you have in the .env

const foo = process.env.uri
Related