skip to Main Content

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?

2

Answers


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

    Login or Signup to reply.
  2. try to access to your variable with process.env
    for exemple process.env.PORT

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search