Toggle between multiple .env files like .env.development with node.js - node.js

I want to use separate .env files for each mode (development, production, etc...). When working on my vue.js projects, I can use files like .env.development or .env.production to get different values for the same env key. (example: in .env.development: FOO=BAR and in .env.production: FOO=BAZ, in development mode process.env.FOO would be BAR, in production i'd be BAZ).
I'm working on an Express server and want to use these same kinds of .env files to store the port, db uri, user, pwd...
I know I can edit the scripts in package.json like this:
"scripts": {
"start": "NODE_ENV=development PORT=80 node ./bin/www",
"start-prod": "NODE_ENV=production PORT=81 node ./bin/www"
}
but this gets messy when using multiple variables.
I've tried using dotenv but it seems like you can only use the .env file. Not .env.development and .env.production.
Can I use the dotenv package or do I need another one? Or could I do this without any package at all?

You can specify which .env file path to use via the path option with something like this:
require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

The above two answers are both slightly off. let me explain. Answer from KyleMit below is missing ./ to indicate current directory.
the ./ indicates current directory in Node.js. The Second . prior to env indicates a hidden/private file. Thats why in KyleMits answer if the env file was not in the root of the PC it would never find it. The simplest way to do it in my opinion is to add a ./
this says "hey computer look in my current directory for this file".
//look in my current directory for this hidden file.
// List hidden files in dir: ls -a
require('dotenv').config({ path: `./.env.${process.env.NODE_ENV}` })
//I reccomend doing a console.log as well to make sure the names match*
console.log(`./.env.${process.env.NODE_ENV}`)

I'm using the custom-env npm package to handle multiple .env files. Just put this at the top of your code:
require('custom-env').env();
and it will load environment variables from the file .env.X, where X is the value of you NODE_ENV environment variable. For example: .env.test or .env.production.
Here is a nice tutorial on how to use the package.

From answers from above:
This is the final result that worked for me.
.env.dev file in src dir.
import path from 'path';
dotenv.config({ path: path.join(__dirname, `./.env.${process.env.NODE_ENV}`)});

For Typescript:
import dotenv from 'dotenv'
dotenv.config({ path: `.env.${process.env.NODE_ENV}` })

Install the dotenv package:
npm install dotenv
We need to get the .env file name based on NODE_ENV, it might be undefined, set default to development:
const envFileName = `.env.${process.env.NODE_ENV || "development"}`
Import the dotenv package and use it:
dotenv.config({ path: envFileName });

The official doc of dotenv does not recommend having multiple .env files.
"Should I have multiple .env files?
No. We strongly recommend against having a "main" .env file and an
"environment" .env file like .env.test. Your config should vary
between deploys, and you should not be sharing values between
environments."

Related

How do you load environment variables from .env and .env.local with dotenv?

This might look like a newbie question, but I am unable to find the way to load environment variables from both .env and .env.local files in node with dotenv.
Is it even possible? How do people load environment variables from both files nowadays if not with dotenv?
Quoting from dotenv's npm page
Should I have multiple .env files?
No. We strongly recommend against having a "main" .env file and an
"environment" .env file like .env.test. Your config should vary
between deploys, and you should not be sharing values between
environments.'
But to use .env.local or .env.test or any other environment.. one at a time is
require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })
If you still want to do it refer to dotenv-flow at
https://www.npmjs.com/package/dotenv-flow
dotenv-flow comes with the feature of overwriting variables at environments.
If .env.local file present dotenv will override .env
dotenv.config();
dotenv.config({ path: `.env.local`, override: true });
dotenv.config({ path: '.env.local' });
dotenv.config();

React environment variable not working in dev

Please put me out of my misery. I see scores of other people had the same issue and I don't see a solution.
I am trying to put my sensitive keys into environment-specific files (.env.development, .env.staging, etc). The keys work fine if I put them in .env but I need this file for some other items which must be pushed up to source control. All of the files are in root (I see that this was a common mistake). Is there something with webpack that is the issue? I have restarted the server instance every time I make a change.
const express = require('express');
const path = require('path');
const app = express();
require('dotenv').config();
console.log('ENV', process.env.NODE_ENV); // this returns "development"
console.log('Hello?', process.env.REACT_APP_HELLO); // this returns "undefined"
As noted I am surfacing the environment correctly.
"start": "SET NODE_ENV=development&& node server/index.js",
from package.json
REACT_APP_HELLO=BLAH
from .env.development
I assume you're in cmd.exe because of the set. Add a space before the &&: "start": "set NODE_ENV=development && node server", (no need to specify index.js. On non-Windows systems this would be NODE_ENV=development node server.
EDIT:
To get .env.development working, change the dotenv line to this: require('dotenv').config({ path: '.env.' + process.env.NODE_ENV }). (source), or the custom-env package: require('custom-env').env(process.env.NODE_ENV). Neither of those inherit from the regular .env though, so if you need that, check out dotenv-flow. I haven't tried the last package, but it seems to have the most features and the least amount of config to get working.

NodeJS not recognizing .env file

I have like 5 NodeJS services running, but I have a problem in one of those.
This is the nodemon.json file:
{
"watch": ["**/*.ts"],
"ext": "ts,json",
"ignore": ["./test/*.ts"],
"exec": "node -r ts-node/register -r dotenv/config Index.ts dotenv_config_path=$(pwd)/.env",
"env": {
"NODE_ENV": "development"
}
}
It's the same as the rest of services. When I run npm run dev I got error messages depending on which value is taking from the .env file, example:
const LOCAL_CONFIGURATION = {
PORT_APP: 8082,
MONGODB: {
SERVER: process.env.MONGO_DTE,
AUTH: {
auth: {
password:process.env.MONGO_PASSWORD,
user:process.env.MONGO_USER
}
},
},
MS_NOTIFICACION: "http://localhost:8089/notificacion",
ELASTIC_PATH: process.env.ELASTIC_PATH,
...COMMON,
};
The first error message is:
ConfigurationError: Missing node(s) option
That message is produced because it's not reading the value from process.env.ELASTIC_PATH, but if I put a hardcoed value like "http://with.the.correct.url" and it tries again to run, I get another error:
Error: Credentials must be provided when creating a service client
That error is because it's trying to read password:process.env.MONGO_PASSWORD and user:process.env.MONGO_USER
etc, so, there's a problem on reading the .env file. I know that .env file has those values, and the file is in UTF-8, without quotes, etc. The .env file is the same file as the other services, it works ok in the rest but I don't know why is not getting read here.
Any idea?
EDIT:
Plus, I put a console.log(process.env); in config.ts file and it shows values like this:
But there's no values from the .env for example, there in the picture there's a value called COMPUTERNAME so if I put console.log(process.env.COMPUTERNAME); I get: IBM-NOT87
Why is not getting the .env file?
Seems like you need to require/configure dotenv. Docs:
As early as possible in your application, require and configure dotenv.
require('dotenv').config()
To further expand on #JBallin answer
you should use this on your app.js
Or if that does not work then you will need to explicitly add it to the file you are wanting to use those Variables
Sharing image, as its sometimes easier to see expanded
code here =>
require('dotenv/config') // require the dotenv/config at beginning of file
const express = require('express')
const mongoose = require('mongoose')
require('dotenv').config({ path: "./sample.env" });
In the file you are using environment variables,
As early as possible, require the "dotenv" and in the config() method, specify the path of the .env file, even if it in your root directory or the same directory where node starts.
The code for requiring and specifying file in the same directory is in the first line in the answer.
Also, for further reading 📖 , you can visit https://github.com/motdotla/dotenv#path
You cat try this.
-> npm i dotenv
and in code add this piece of code
require('dotenv').config({
path: 'your path here'
})
Install dotenv package
npm install --s dotenv
And add this require("dotenv").config(); in index.js/ts file.

Environment Variables don't work in a nested JS file (React)

I'm trying to use environment variables in create-react-app.
I've prefixed all of the variables in my .env file with REACT_APP_ and installed/required dotenv.
However, I'm suspecting that the reason why my .env values aren't being read is because the script in which I'm calling them from isn't in the root folder where my .env file is located.
There's a quick overview of my project structure below
ROOT:
.env
VIEWS (folder):
view.js
I'm trying to access the .env variables in view.js by calling process.env.REACT_APP_MYVAR but it either doesn't return a value or returns something that isn't a string (which is the error my API is throwing, but it could be because that call is returning undefined)
Is this a known issue or is there any way I can fix this? I could just take the script out of that folder and put it in the root of my app but I'd rather keep the structuring of the app consistent
You don't need to "install/require" dotenv. If you are using create-react-app, this functionality is available with no additional install required.
You indicate that .env is in your root, but I suspect it may not actually be in your root. From your description, it sounds like you have it in your root source folder, but the .env file belongs in the root directory of your app (i.e. the same directory as your package.json file).
Here's a CodeSandbox (using create-react-app) that demonstrates using an environment variable in a nested file:
The contents of this sandbox includes:
.env (in the same directory as your package.json file)
REACT_APP_MYVAR=Here is my value for REACT_APP_MYVAR
src/index.js
import React from "react";
import ReactDOM from "react-dom";
import View from "./views/View";
function App() {
return <View />;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
src/views/View.js
import React from "react";
const View = () => {
return <div>My Var: {process.env.REACT_APP_MYVAR}</div>;
};
export default View;
The result that gets rendered is:
My Var: Here is my value for REACT_APP_MYVAR
The environment variable can be used in any of the js source files regardless of level of nesting.
If this doesn't help with your problem, please show the exact contents of your .env and view.js.
remove dotenv. Here is my git-repo for accessing REACT_APP_KEY. tell me if this solves your problem.
git-repo
Change .env to .env.development.local
Actually .env also work but if you have other .env.* file it will override .env,
.env is least priority in create-react-app
if you run project with npm start this file .env.development.local will override other env files
priority goes like this, form left to right
npm start: .env.development.local, .env.development, .env.local, .env

Node JS to load dotenv with forever

I would like to ask if anyone know how to run forever that can load .env file.
Currently if we run forever start app.js, process.env.foo become undefined.
TLDR, You need to add the --workingDir path to your cronjob line.
forever -c "node -r dotenv/config" --workingDir app-workdir-path start app.js
Many previous answers but none of them really solve this specific use case.
To run forever with dotenv you'll need to do two things.
First is we need to use dotenv's preload feature, meaning we need forever to pass a node parameter to the process. we can do it by using the -c COMMAND flag forever has.
The second thing is related to how the dotenv package works. here is snippet from the source code:
let dotenvPath = path.resolve(process.cwd(), '.env')
What does process.cwd() do?
The process.cwd() method is an inbuilt application programming interface of the process module which is used to get the current working directory of the node.js process.
Meaning dovenv package want's to load the .env file from the working directory. so to solve this issue we can use forever's --workingDir flag to specify the actual working directory of the process.
And the final command will look like this:
forever -c "node -r dotenv/config" --workingDir app-workdir-path start app.js
Where app-workdir-path is the absolute path to the project directory.
What worked for me was to specify the full path:
require('dotenv').config({ path: '/opt/api/.env' });
You can use dotenv package for this purpose. On your app entry, do this
require('dotenv').config({ path: '.env' })
If you have added .env file in root directory of your project then you can use like this
require('dotenv').config()
Or if you created your file .env with different location then in your code use
require('dotenv').config({path : '/your/path/.env'})
I found your question and had the same issue. I don't think dotenv works with forever - At least not that I was able to get working. However, I think there's a workaround that you could employ. I was able to specify environment variables on the command line preceding the forever command, and forever passed those environment variables to my node app.
~$ ENV=production forever start yourApp.js
For more information about specifying environment variables on the command line, checkout this Stack Overflow question.
I've had this issue with multiserver forever config.
You should include --workingDir parameter pointing to the root of your project directory in case you've included .env file in your root and using dotenv
Example:
Flexible config with minimum "hard coded" values
.env placed in root directory
"dotenv" used in form of dotenv.config()
Code for multiserver config in case of one server:
const fs = require('fs');
const path = require('path');
let foreverConfig = [
{
uid: 'scheduledJobsServer',
append: true,
watch: true,
script: 'scheduledJobsServer.js',
sourceDir: path.join(__dirname, '/server'),
workingDir: path.join(__dirname)
},
{
uid: 'mainServer',
append: true,
watch: true,
script: 'server.js',
sourceDir: path.join(__dirname, '/server'),
workingDir: path.join(__dirname)
}
];
try {
fs.writeFileSync(
path.join(__dirname, '/foreverConfig.json'),
JSON.stringify(foreverConfig),
{ encoding: 'utf8' }
);
let consoleMessage = 'Init script success';
console.log('\x1b[42m%s\x1b[0m', consoleMessage);
} catch (e) {
console.log('Init script error:', e);
process.exit(1);
}
Then run forever start foreverConfig.json
Sometimes you have to call the node script from another directory. For instance, when running cron jobs. Here is what you can do:
cd /path/to/script/ && /usr/bin/forever start /usr/bin/node script.js
Now the .env file will load.
The easiest command for me is
dotenv -e .env forever start build/index.js

Resources