Environment variables - undefined - javascript

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

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;

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

Variables in .env file is not updated. How to reset

Im building an app with Quasar (vue) where I am using .env file to store my keys to the database. I was going to switch to another instance but after I changed the keys in the env file it still calls the old values of the variables. They seemd to be cached in some way.
Im using dotenv to call the env file.
I have tried of course to reset the history in browser as well as running
npm cache clean --force
How can I reset the env files?
Quasar handles env variables through quasar.config.js file, not separate .env files. See the documentation.
quasar.config.js
module.exports = function (ctx) {
return {
// ...
build: {
// passing down to UI code from quasar.config.js
env: {
API: ctx.dev
? 'https://dev.api.com'
: 'https://prod.api.com'
}
}
}
}
As noted in the docs, if you do want to use .env files you'll have to add the dotenv package to your project and point quasar.config.js to use the env variables set with dotenv
build: {
env: require('dotenv').config().parsed
}

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

Categories

Resources