Node.js Express custom process.env variables not accessible from all files - javascript

I am working on an app with Node.js and express and am using the 'dotenv' package to config/load my variables from the .env file. My issue is that I can only access the variables I defined in the main index.js file and not in all of the project files. I would like to be able to do so to do stuff like set up the db config in a separate file.
database=application`
And this is what I have in index.js:
`const dotenv = require('dotenv');
dotenv.config({ path: './config/config.env' })
const HOSTNAME = process.env.HOST || 'localhost';
const PORT = process.env.PORT || 3000;`
As I said, I have no issue accessing these variables in the index.js file but if I try to access process.env.DB_SERVER for example from a different file, the value is undefined.
Any help or suggestions would be much appreciated! Thanks!!

Note that all imports modules in your index.js file are evaluated before index.js is being evaluated.
This means that dotenv.config({ path: 'config/config.env' }); is being executed only after other imported were executed, so inside those modules the DB_SERVER environment variable is not yet loaded.

Related

In Next.js, Is there a way to change the location of the .env file to be outside of the app's folder?

I'm making a project that contains a Next.js app and my .env file is located in the project's root.
How do I make Next.js look for the .env file anywhere except the app's root folder?
I already tried using the dotenv package, but unfortunately, that doesn't work.
In your next.config.js file configure the dotenv package as this.
const path = require('path');
const dotenv = require('dotenv');
dotenv.config({ path: path.join(__dirname, '/path/to/.env') });
To change the location of the .env file, install the 'dotenv' package and add it to your next.config.js file:
dotenv.config({path: '../.env'})
(In my case the path is ../.env to go one folder up)
To be able to access the environment variables on the client side declare them in the next.config.js file like that:
const nextConfig = {
...
//to be able to use the environment variables on the client side
//==============================================================
env: {
EXMAPLE_ENVIRONMENT_VARIABLE: process.env.EXMAPLE_ENVIRONMENT_VARIABLE,
},
...
}
module.exports = nextConfig;

How to access environment variables client-side (Node.js)

I have declared some environment variables on my server using dotenv, and I want to be able to access one of them on my client-side code
I have my .env file set up like so:
NODE_ENV='development'
DEF_USER='admin'
then I have my config.js file where I load the variables from my env file:
const dotenv = require('dotenv');
const path = require('path');
dotenv.config({
path: path.resolve(__dirname, `../environments/${process.env.NODE_ENV.trim()}.env`)
});
module.exports = {
NODE_ENV: process.env.NODE_ENV || 'development',
DEF_USER: process.env.DEF_USER || 'admin'
};
How can I acces my DEF_USER variable on my client's code? I can access NODE_ENV with process.env.NODE_ENV, but no such luck with DEF_USER.
I should mention that my server and my client code is in separate directories.
Also, I didn't used create-react-app.
I also tried by installing webpack in my client but it trows me a lot of errors.
"You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name"
This is from React documentation, hope it helps. Link: https://create-react-app.dev/docs/adding-custom-environment-variables/

How to Set .env with JS

I have this, from https://npm.io/package/node-calendly-sdk.
calendly_client = new Calendly("YOUR-API-TOKEN")
I'm confused on how to set .env varibles in js
Env variables are a set of values, generally to store sensitive data that shouldn't be in the code.
In nodejs, you can add the npm package dotenv with: npm i dotenv, then, you have to create a file named .env in the root directory of your project and define your variable like:
.env file:
API_KEY_TOKEN = "some value"
Then, at the very beginning of your nodejs file, write: require("dotenv").config(); and that's it, you can access your .env variables with process.env
Full example:
require("dotenv").config();
calendly_client = new Calendly(process.env.API_KEY_TOKEN );
For a complete documentation visit dotenv

Use Environment Variables in different js File in Node Express App

I want to use environment Variables in a different js File in an Express App. I tried many things, googled a lot, and didn't make it work.
My Setup:
I have an Express app with an index.js to serve a html page with javascript and css files. There I import the module dotenv and want to use Environment Variables inside the .env file. Printing out the variables in the index.js is working. The Code of my index.js looks like this:
const express = require("express");
const app = express();
const path = require("path");
const router = express.Router();
const dotenv = require("dotenv").config();
app.use(express.static("."));
Now I want to use the variables inside my JavaScript-File (main.js).
I tried different things...
Using exports. -> I can't import the variables because main.js is not a module. -> If I make main.js to a module, my included functions won't work.
Use requireJS -> This was not successful. Probably I made something wrong...
Use const dotenv = require("dotenv"); inside main.js -> Don't work because "require" is not defined..
Use the variables process.env.user inside main.js -> "Process is not defined"
I think that the way I serve and using express is wrong, but I don't know how and what to change and didn't find a short way.
Summarized:
I serve a website with an express app and want to use environment variables to don't publish access keys. I also want to later use these environment variables by building a docker container. I don't know how to use or export environment variables from the index.js to another js-File where my function for the website is located.
This is my first post. If I didn't make it clear I will be happy if you tell me what you need to help me.
Try placing the dotenv require statement at the top like this,
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const path = require("path");
const router = express.Router();
app.use(express.static("."));
This should work.
Further, in order to use environment variable, you just need to do this,
process.env.VARIABLE_NAME
If I didn't make anything clear please do let me know, I am also a beginner like you :)

If I set env vars using dotenv and PM2 ecosystem.config.js, which one will Node use?

I assume PM2 appends env vars the 'native' system way at startup, something like:
MYVAR=hey; node app.js
The difference with the dotenv npm package is it MUST append vars another way, because it works inside the script (it can't do MYVAR=someothervar; node app.js because the program is already started), so it works like this:
dotenv.config() //reads .env file and appends stuff to process.env at runtime
Now say PM2 launches MYVAR=hey; node app.js and then inside app.js we run dotenv.config() that reads an .env file containing MYVAR=foo. Which var will be in process.env?
ecosystem.config.js
{
//...standard pm2 config above
env: {
MYVAR: 'ecosystem',
},
}
.env/dotenv
MYVAR=dotenv
Code
dotenv.config()
console.log(process.env.MYVAR)
dotenv.config() will not overwrite variables if it sees they already exist in the process.env (that they've been assigned the PM2 MYVAR=foo; node app.js way.
So process envs set before launch will take precedence.
This is actually in the README of dotenv.
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.
https://www.npmjs.com/package/dotenv#what-happens-to-environment-variables-that-were-already-set
If you absolutely need to override existing env vars - use the dotenv-override package.

Categories

Resources