Search code examples
javascriptnode.jsdotenv

Dotenv unable to overwrite key value pair


I am trying to implement environment variables using dotenv on my node server, however I am having trouble loading them in from the .env file which is located in the root. When I run const dotenv = require("dotenv").config({debug: true}); I encounter the following message: "USER" is already defined in process.env and will not be overwritten

Additionally when I try to load the page, it encounter the following error: ER_DBACCESS_DENIED_ERROR: Access denied for user ''@'localhost' to database '_api'

.env:

USER=root
PASS=

Solution

  • From the Variables overwriting/priority.

    Environment variables that are already set will not be overwritten, that means that the command line variables have a higher priority over all those defined in env files;

    And this What happens to environment variables that were already set?

    We will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.

    If you want to override process.env you can do something like this:

    const fs = require('fs')
    const dotenv = require('dotenv')
    const envConfig = dotenv.parse(fs.readFileSync('.env.override'))
    for (const k in envConfig) {
      process.env[k] = envConfig[k]
    }