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

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/

Related

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

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.

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;

Allowing access to process and process.env in Webpack 5

I'm using environment variables to set the basename of a react-router-dom BrowserRouter. However, Webpack 5 does not allow accessing environment variables.
From other stackoverflow questions, I've seen that using this:
new webpack.ProvidePlugin({
process: 'process/browser',
})
makes process available. However, process.env is empty ({}).
Also, if I use
const dotenv = require('dotenv')
dotenv.config();
console.log(process.env);
I can see the variables in my .env file are present in process.env in the config file but I can't find a way to make them accessible from process.env in the code.
I have tried:
new Dotenv({ systemvars: true })
And some other plugins suggested in Webpack: Bundle.js - Uncaught ReferenceError: process is not defined but adding any other plugin other than the 'process/browser' makes process not defined again.
I know there's a reason behind not allowing the use of process.env but I do need it.
Did you check this?
DotenvPlugin
The third-party DotenvPlugin (dotenv-webpack) allows you to expose (a subset of) dotenv variables:
new Dotenv({
path: './.env', // Path to .env file (this is the default)
safe: true, // load .env.example (defaults to "false" which does not use dotenv-safe)
});

Environment variables - undefined

I want to use environment variables. I made a custom react app environment.
Everything is ok, the app runs properly, no errors. But the variables from .env file gives undefined and the process.env gives an empty object.
I added dotenv and REACT_APP prefix to the variable.
And in webpack.config.js file i added node: { fs: 'empty' }, from here
Here are my configurations.
Folder structure:
PROBLEM SOLVED:
Uninstall dotenv
Remove these two from main app.js file:
const dotenv = require('dotenv')
dotenv.config();
Remove the flag --env from npm start script.
Remove node: { fs: 'empty' } from webpack.config.js file
Install dotenv-webpack, and follow the instructions from there.
No need for REACT_APP prefix.
Fixed configuration files
You have to put REACT_APP in front of the variable name you want to have
eg:/
REACT_APP_YOUR_VAR="something"
You don't need to install Dotenv or something else, because React has its own.
try https://www.npmjs.com/package/dotenv to use .env variables
In your entry JS file add below code snippet (maybe your ./src/assets/js/app.js)
const dotenv = require('dotenv')
dotenv.config()
and restart your app.
You can use webpack.DefinePlugin
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
})
],
Then in your code simply use process.env.NODE_ENV to access ENV variable

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