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?
asked Feb 11, 2017 at 23:44
user1354934user13549348,8911717 gold badges6464 silver badges8888 bronze badges
Sorry for picking up old question, but
react-scripts actually uses dotenv library under the hood.
With [email protected] and higher, you can work with environment variables this way:
.env
REACT_APP_BASE_URL=http://localhost:3000
App.js
const BASE_URL = process.env.REACT_APP_BASE_URL;
See docs for more details.
answered Jun 19, 2019 at 13:23
Dmitry DemidovskyDmitry Demidovsky8,26744 gold badges2525 silver badges2323 bronze badges
15The 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.
answered Feb 11, 2017 at 23:53
SoviutSoviut92k5353 gold badges209209 silver badges283283 bronze badges
2Actually, 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
answered Apr 18, 2019 at 7:21
sergiosergio63488 silver badges1313 bronze badges
API_URL=http://localhost:8000
$ npm install --save-dev dotenv
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)
]
};
60.7k3232 gold badges155155 silver badges183183 bronze badges
answered Jul 21, 2020 at 18:46
KhurramKhurram65055 silver badges1212 bronze badges
0For developers using the VITE + React setup, it's important to note that Vite utilizes dotenv behind the scenes, making usage quite straightforward. Ensure all .env variables are prefixed with 'VITE', as follows:
VITE_APP_API_URL=https://your_backend_url/api
Then, incorporate them into your code like so:
import.meta.env.VITE_APP_API_URL
For more informations, read the documentation: https://vitejs.dev/guide/env-and-mode
answered May 15, 2024 at 12:16
Miro GrujinMiro Grujin72677 silver badges1515 bronze badges
To set up a .env file in a React project, follow these steps:
Create a new file named .env
at the root of your React project.
Add the environment variables in the .env file in the format VARIABLE_NAME=VALUE
. For example:
REACT_APP_API_URL=https://api.example.com
REACT_APP_API_KEY=YOUR_API_KEY
Note: It is recommended to prefix your environment variables with REACT_APP_
to ensure they are picked up by React's build process.
Save the .env file.
Restart your development server or build process to load the environment variables.
In your React components, you can access the environment variables like this:
const apiUrl = process.env.REACT_APP_API_URL;
const apiKey = process.env.REACT_APP_API_KEY;
Make sure not to commit the .env file to version control systems like Git, as it might contain sensitive information like API keys and other credentials.
If you are using Create React App, it automatically picks up the variables from the .env file. However, if you are using a custom setup, you might need to configure your build tools accordingly to support .env files.
answered Aug 2, 2023 at 11:20
SufiyanSufiyan2111 silver badge44 bronze badges
0To use dotenv variables in a React project, Here's how you can do it using a config.js file in the src folder:
REACT_APP_API_URL=http://localhost:5000
// src/config.js
export const API_URL = process.env.REACT_APP_API_URL;
import React from 'react';
import { API_URL } from './config';
const MyComponent = () => {
return (
<div>
<p>API URL: {API_URL}</p>
</div>
);
};
export default MyComponent;
answered Mar 4, 2024 at 8:26
2Nowadays if you're using Vite
, you can do the following:
.env
file and write your variables whose names are prefixed with VITE_
(vite will only expose those variables to the client that start with VITE_
)import.meta.env.<VARIABLE_NAME>
Example:
In .env:
VITE_PASSKEY=1234 #exposed to client by vite because of 'VITE_' prefix
ANOTHER_PASSKEY=5555 #cannot be accessed from client
Now in any js/jsx file of your app:
const myPass = import.meta.env.VITE_PASSKEY; //1234
Restart your server after doing these if you are not getting them yet.
WARNING: DO NOT PUT SENSITIVE INFORMATION ON THE CLIENT SIDE .env! It will be visible to the client the moment you use any of the environment variables in your frontend code (actually it'll be accessible even if you don't use it in your frontend code). The attacker can even modify your code to invoke some of the .env variables and access its values. Or monitor the network activity to see what you're sending. There are so many easy ways to access client side .env data. Keep all of your critical variables in your backend's .env for safety. Client side .env is only for things that you're comfortable with the client knowing, like the backend URL or some port, etc.
answered Jul 5, 2024 at 5:33
Start asking to get answers
Find the answer to your question by asking.
Ask questionExplore related questions
See similar questions with these tags.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4