Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dotenv not reading variables inside .env file

I’m trying to use dotenv to load the following .env file:

PORT=4000
BASE_URL=http://127.0.0.1:${PORT}/
require('dotenv').config('.env')

For some reasons, dotenv does not resolve ${PORT} to 4000, instead it just returns a plain string like this:

{
  parsed: {
    PORT: '4000',
    BASE_URL: 'http://127.0.0.1:$PORT/',
  }
}

How can I make dotenv read variables inside .env file?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use dotenv-expand because dotenv doesn’t support variable substitution using ${} syntax.

to use dotenv-expand install

npm install dotenv-expand

add require dotenvExpand keep the same .env file with ${} syntax

var dotenv = require("dotenv");
var dotenvExpand = require("dotenv-expand");

var result = dotenv.config();
dotenvExpand.expand(result);

console.log(result.parsed);

The output will return like:

{
  PORT: '4000',
  BASE_URL: 'http://127.0.0.1:4000/'
}

Output:

output of env substitution

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading