I defined username and password in config.env
file and tried to retrieve with dotenv package.
When I try to retrieve username
, it gets the hostname. Regardless if I define all lowercase letters or uppercase letters; it returns the computer hostname.
Is it with the process.env.username
having some variable name collision, and by design it would read the hostname for process.env.username
?
Here is snippet code from app.js:
const express = require('express')
const app = express();
const dotenv = require('dotenv')
// Setting up the post for server
dotenv.config({
path: './utils/config.env',
override: true
})
console.log(`*** Username: ${process.env.USERNAME}`)
console.log(`*** Username: ${process.env.USER_NAME}`)
console.log(`*** Username: ${process.env.UNAME}`)
console.log(`*** Password: ${process.env.password}`)
const PORT = process.env.PORT;
app.listen(PORT, () => {
console.log(`Server has started on port: ${process.env.PORT} in ${process.env.NODE_ENV} mode.`)
})
Here is what is inside config.env file:
PORT = 3000
NODE_ENV = development
USERNAME = USERNAME1
USER_NAME = USERNAME2
UNAME = USERNAME3
password = password@123
How should I understand this and (I guess) what is the recommended way of defining username and password in config.env
file when we deal with NodeJS?
When I added '_' (like USER_NAME, or any other form of 'username'); then it works as expected.
Dotenv by default will not overwrite existing shell variables.
You can configure dotenv with the override option to work around this.
require('dotenv').config({
path: './utils/config.env',
override: true,
});
This will ignore any existing environment variables with the same names as those in your config.env
file.