Is it possible to use dotenv in a react project? - javascript

I am trying to set some environment variables (for making API calls to dev/prod endpoints, keys depending on dev/prod, etc.) and I'm wondering if using dotenv will work.
I've installed dotenv, and I am using webpack.
My webpack entry is main.js, so in this file I've put require('dotenv').config()
Then, in my webpack config, I've put this:
new webpack.EnvironmentPlugin([
'NODE_ENV',
'__DEV_BASE_URL__' //base url for dev api endpoints
])
However, it is still undefined. How can I do this correctly?

Sorry for picking up old question, but
react-scripts actually uses dotenv library under the hood.
With react-scripts#0.2.3 and higher, you can work with environment variables this way:
create .env file in the root of the project
set environment variables starting with REACT_APP_ there
access it by process.env.REACT_APP_... in components
.env
REACT_APP_BASE_URL=http://localhost:3000
App.js
const BASE_URL = process.env.REACT_APP_BASE_URL;
See docs for more details.

The short answer is no. A browser cannot access local or server environment variables so dotenv has nothing to look for. Instead, you specify ordinary variables in your React application, usually in a settings module.
Webpack can be made to take environment variables from the build machine and bake them into your settings files. However, it works be actually replacing strings at build-time, not run-time. So each build of your application will have the values hard-coded into it. These values would then be accessible through the process.env object.
var nodeEnv = process.env.NODE_ENV;
Additionally, you could use the DefinePlugin for webpack which lets you explicitly specify different values depending on your build target (dev, prod, etc.). Note that you have to JSON.stringify all values passed into it.
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
}),
This is fine for any sort of public details but should never be used for any sort of private keys, passwords or API secrets. This is because any values baked in are publicly accessible and could be used maliciously if they contain sensitive details. For those sorts of things, you need to write some server-side code and build a simple API which can authenticate with the 3rd party API using the secrets, then pass the relevant details along to your client-side application. Your server-side API acts as an intermediary, protecting your secrets while still getting the data you need.

Create .env file
API_URL=http://localhost:8000
Install dotenv npm package
$ npm install --save-dev dotenv
Config webpack to add env variables
const webpack = require('webpack');
const dotenv = require('dotenv');
module.exports = () => {
// call dotenv and it will return an Object with a parsed key
const env = dotenv.config().parsed;
// reduce it to a nice object, the same as before
const envKeys = Object.keys(env).reduce((prev, next) => {
prev[`process.env.${next}`] = JSON.stringify(env[next]);
return prev;
}, {});
return {
plugins: [
new webpack.DefinePlugin(envKeys)
]
};
Great job! Enjoy React and dotenv.

Actually, you can use dotenv in your React app with webpack. Moreover, there are several ways of doing it. However, keep in mind that it's still a build-time configuration.
A similar way to the answer above. You import dotenv in your webpack config and use DefinePlugin to pass the variables to your React app. More complete guide on how you can inject your .env files depending on current configuration could be found in this blog.
Using a dotenv-webpack plugin. I personally find it really convenient. Let's say you have environments: dev, staging and prod. You create .env file for each environment (.env.dev, .env.staging, etc). In your webpack configuration you need to pick a correct file for the environment:
const Dotenv = require('dotenv-webpack');
module.exports = (env, argv) => {
const envPath = env.ENVIRONMENT ? `.env.${env.ENVIRONMENT}` : '.env';
const config = {
...
plugins: [
new Dotenv({
path: envPath
})
]
};
return config;
};
When you build the app for a particular environment, just pass the environment name to webpack:
webpack --config webpack.config.js --env.ENVIRONMENT=dev

I Just created a config.json in the source folder:
{
"api_url" : "http://localhost:8080/"
}
then required it in the file I needed it
const config = require('./config.json');
and used config.api_url

Related

How to specify which .env file is used in Cypress Component Tests

i've been trying to figure out how to specify which .env file to use when running Cypress Component tests for a while now but can't seem to figure it out or find any information about it online.
I've noticed when you mount a Component in Cypress and run some Component Tests, the component will pick up process.env variables from the .env file by default. However, I would instead like Cypress to pick up process.env variables from my .env.test file. Does anyone know how to specify which .env file your component should get process.env variables from when running component tests?
I am currently just running the following command from my package.json file "test-e2e": "cypress open". This opens the Cypress test runner where I can select Component Testing and then select a spec file to run tests against. The component in question uses some process.env variables which I can see are being taken from the .env file which seems to be the default. I can't find any flags I can add to my npm command to instead tell Cypress to take them from the .env.test file instead.
Any help would be much appreciated!
You want to do something like this answer How can I get Vite env variables.
Note that the .env section of config is outside of component or e2e sections (common to both).
const { defineConfig } = require("cypress");
const dotenv = require('dotenv')
const env = dotenv.config('./.env.test').parsed
module.exports = defineConfig({
'component': {
// component config here
},
env: {
login_url: '/login',
...env, // merge here with spread operator
},
});

Vue.js environment variables without vue-cli

What is the best way to load environment variables for Vue.js app without using vue-cli? In vue-cli way you just update the .env files and those variables should be available in Vue.js app like this: https://cli.vuejs.org/guide/mode-and-env.html#example-staging-mode
I am using Symfony Webpack Encore and have no vue-cli installed, how could I pass my environment variables into entire Vue application?
just create a .env file and create you variable like this VUE_APP_XXXXX
you notice the VUE_APP make sure all variable has the VUE_APP prefix like.
VUE_APP_API_URL
for development .env.development.
for production .env.production
Currently this looks like a decent way to load the configs: https://github.com/symfony/webpack-encore/issues/567
First install the dotenv package and then use this on my webpack.config.js:
const dotenv = require('dotenv');
.configureDefinePlugin(options => {
const dotenvOptions = {};
const envConfigPath = `.env.${process.env.NODE_ENV}`;
if (fs.existsSync(envConfigPath)) dotenvOptions.path = envConfigPath;
const env = dotenv.config(dotenvOptions);
if (env.error) {
throw env.error;
}
options['process.env'].PMP_API_BASE_URI = JSON.stringify(env.parsed.PMP_API_BASE_URI);
})
If .env.dev.local is needed then provide NODE_ENV=dev.local while running npm run build command.

Cannot find node module in rails stimulus controller

I have a problem with importing an npm package that I have created into my rails application.
I'm unsure if the problem is in the way I have created the node package or with the rails app.
The package is very simple -> https://www.npmjs.com/package/test-release-stuff
Now when I'm trying to import it into rails (I install it vie yarn and then see it's in the node modules) and I try to import it into my stimulus controller it tells me that it can't find the module. The error literally says:
Error: Cannot find module 'test-release'stuff'
How I'm importing the module?
I'm doing import foo from 'test-release-stuff'
One thing to note is that when I tried that in a simple react todo app it was imported without any issues.
I have a feeling that it might be something with the webpacker config in my rails app (below is the config) or that it might be something with the node packaga packgage.json file, there might be something incorrect there.
const { webpackConfig, merge } = require('#rails/webpacker');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const plugins = [];
if (process.env.ANALYZE === 'true') {
plugins.push(new BundleAnalyzerPlugin());
}
const customConfig = {
resolve: {
extensions: ['.css'],
},
plugins: plugins,
};
module.exports = merge(webpackConfig, customConfig);
then in the production/development/test files I have something like this:
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
const webpackConfig = require('./base');
module.exports = webpackConfig;
It's a rails 6 project.
Turns out it was neither rails app fault or the node package fault.
I'm running the project inside the container. Although I installed once the previous version of that node package, when updating it, the changes were not properly reflected inside the container - I assume at some point the actual yarn command was not firing or that there was some caching involved.
After properly bringing the containers down, running docker-compose build and docker-compose up the changes were reflected and I can use the node package.

Environment variables in Typescript with Webpack

I am having trouble declaring globals in Typescript, using Webpack's DefinePlugin. I was hoping to get some input on what I am doing wrong.
I created an environment variable in my .bash_profile:
export API_KEY_GOOGLE_MAPS=xxxxxxxxxxxxxxxx
In my webpack.config.js, I have the following lines:
...
plugins: [
new webpack.DefinePlugin({
API_KEY_GOOGLE_MAPS: JSON.stringify(process.env.API_KEY_GOOGLE_MAPS),
}),
],
...
Inside index.tsx (I am using React), I do the following:
declare var API_KEY_GOOGLE_MAPS: string;
console.log(API_KEY_GOOGLE_MAPS)
This produces the following error, at the line containing console.log:
ReferenceError: API_KEY_GOOGLE_MAPS is not defined
Does anybody have any leads?
The other answers require create-react-app so I will offer mine.
First, add the plugin to your Webpack configuration:
const webpack = require("webpack");
module.exports = {
// ...
plugins: [
new webpack.DefinePlugin({
MY_ENV_VAR: JSON.stringify(true),
}),
],
};
Next, declare the variable in TypeScript:
declare var MY_ENV_VAR : string | undefined;
Finally, you can access the variable in your code:
console.log(MY_ENV_VAR);
create-react-app environment variables should be prefixed with REACT_APP_:
Note: 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. Changing any environment variables will require you to restart the development server if it is running.
from the "Adding Custom Environment Variables" documentation.
You should be adding these environment variables to your .env file(s) in place of adding these to your .bash_profile file. The appropriate file will be picked up depending on the build (i.e. start or build), and the application will be easier to share and deploy.
The way I do it is to have a .env file(add it to .gitignore) in the root of my project files.
Within that file I define my project environment variables(additional variables can be separated by adding each to it's own line):
NODE_ENV=development
Then using the dotenv npm module I can access the values in any webpack file(or server side expressJS file for example).
// in the command line
$ npm install --save dotenv
// at the top of the webpack config file
require('dotenv').config();
// in the plugins of the webpack config
plugins: [
new webpack.DefinePlugin({
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
],
Now I can reference it within my app being transpiled by webpack:
console.log(NODE_ENV); // development
Answering my own question: my project was generated using create-react-app, and according to its documentation, environment variables are accessed this way:
console.log(process.env.API_KEY_GOOGLE_MAPS)
webpack.DefinePlugin() is not required.

Define globals when bundling to umd or commonjs

I have a client-side application which makes use of some browser global properties like Element or document.
I'd like to run my application in node.js as well and currently I am overriding those globals with the domino dom implementation in my server like so:
const domino = require("domino");
const domimpl = domino.createDOMImplementation();
const document = domimpl.createHTMLDocument();
Object.assign(global, Element: domino.impl.Element, document};
const myApp = require('my-app');
I am currently using rollup to bundle different versions of my-app, how can I have rollup do this for me automatically for the _server version of my-app so consumers of my-app don't have to do that?
I was thinking of writing my own rollup plugin but I feel like overriding globals seems like a common practice.
TLDR; Use separate entry file instead of a rollup plugin.
Simply add the following instead of a rollup plugin
if (typeof window ==== "undefined") {
const domino = require("domino");
const domimpl = domino.createDOMImplementation();
const document = domimpl.createHTMLDocument();
Object.assign(global, Element: domino.impl.Element, document};
}
// my-app code
You might be worried about domino entering client side code. To fix this, use separate bundles for server and client, wrap the above mocking code in a separate file and use the following in your my-app’s main file meant for the server bundle, an approach similar to how React ships production and development bundles - conditional imports.
Server main file
require(‘./globals-mocking’);
// my-app client code
Client main file
// my-app client code only
package’s main file
if (SERVER_ONLY) {
module.exports = require('./my-app-server.js');
} else {
module.exports = require('./my-app-client.js');
}
Use rollup's replace plugin and define SERVER_ONLY (https://github.com/rollup/rollup-plugin-replace#usage) for server entry only. If you use UglifyJS or simlilar tool that eliminates dead code, you wont have domino and duplicated server code.
EDIT: Noticed a minor issue. Condition should be if (SERVER_ONLY) {. Use the following definition along with it for the server entry file.
plugins: [
replace({
SERVER_ONLY: JSON.stringify(true)
})
]

Categories