Allowing access to process and process.env in Webpack 5 - javascript

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)
});

Related

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/

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.

Cannot specify url in .env file vue cli 3

I'm referring to the documentation about environment variables in vue cli 3.
I'm able to set it up and get simple variables to show up but my url in the .env file doesn't show up.
Contents of the .env file:
FOO=bar
VUE_APP_SECRET=secret
API_URL="https://staging.something.org"
Here is how I'm viewing the env:
console.log(process.env)
BASE_URL: "/"
NODE_ENV: "development"
VUE_APP_SECRET: "secret"
The API_URL is not visible, am I doing something wrong?
Refer to the documentation.
Only variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. You can access them in your application code:
Your VUE_APP_SECRET is accessible because it's prefixed with VUE_APP_. Use VUE_APP_API_URL instead of API_URL to access it in your frontend.
Since CLI 3, Vue recognizes variables in dotenv only when adding the prefix VUE_APP_
When making changes, restart CLI.

React + webpack: 'process.env' is undefined

I'm trying to run the hot dev server on our site with webpack; the site uses ReactJS, which has this code in it:
if (\"production\" !== process.env.NODE_ENV) // etc
When not running hot-swap it's fine, but with the hot-swap, it gets run, resulting in the error:
TypeError: process.env is undefined
The code looks like this:
The project is modelled after https://github.com/webpack/react-starter which does work; so the question is; what error have I made in the config file and/or how do I go about looking for the error when the 'production' compilation works just fine?
I've posted the gist of the webpack config file.
In your webpack config, there are two options that can affect process.env:
When you specify config.target (see config.target)
When you define the process.env variable via DefinePlugin
Looking at your code, it looks like process.env might be undefined when both options.prerender and options.minimize are false.
You could fix this by always using an environment that defines process.env (ex: node), or by using DefinePlugin to assign a default value to the variable yourself.
This is the simplest way:
new webpack.EnvironmentPlugin( { ...process.env } )
Add that to your list of webpack plugins.

Categories

Resources