score:57
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.
score:-7
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
score:15
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
andprod
. 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
score:15
- 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.
score:365
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.
Source: stackoverflow.com
Related Query
- Is it possible to use dotenv in a react project?
- Is it possible to use React in Django project "partially"?
- Is it possible to use different version of the same libraries in my react project
- Is it possible to use if...else... statement in React render function?
- Is it possible to use React without rendering HTML?
- Is it possible to use async / await in React JS?
- Is it possible to use react-datepicker with react hooks forms?
- Is it possible to use Material UI library with React Native?
- Is it possible to run React project without npm start?
- Cannot import materialize-css in React project to use Chips
- Use one React project within another
- How to use Antdesign with tailwindcss together in a React Project
- how is it possible to use flowtype to define a prop in react context of a component?
- How do I properly use ASP.NET Core Web Application React project template
- Is it possible to use React Hooks outside of functional component, or i have to use mobx or redux?
- Is it possible to use Enzyme's snapshots on React fragments?
- How to use images from sharp module in React and Webpack project
- React router use in library - not possible to use useHistory()
- Trying to use GoogleSignIn in React Native then Possible Unhandled Promise Rejection (id: Error: DEVELOPER_ERROR
- Is it possible to use spread out operator to set the react component props?
- Is it possible to use only Amplify Auth in a react app in isolation?
- I would like to use TypeScript and React in Laravel Project
- Is it possible to export react component as function in non-react project
- Is it possible to use experimental version of React while using Create React App
- Is it possible in React Typescript to use a component prop interface with another prop?
- Is it possible to use MaterialUI with React and css modules and access the theme inside the css module file?
- Is it possible to use Onsen UI 2 in Meteor with React
- is it possible to use material ui tabs and still use react router?
- Is it possible to use React Hooks in class component by using HOC(Higher Order Component)?
- is it possible to use inline if with react components?
More Query from same tag
- How can I better animate a modal using CSS?
- Mock response value in custom Ajax function using Jest
- How to pass argument in command line with npm and read it in react javascript code
- Undefined Error: TypeError: Cannot read properties of undefined (reading 'Icon')
- Handle Array of Object manipulation
- useContext is giving me problems with my react router dom
- mui-datatables: How to display data from an AP with custom columns?
- React, cannot read this.props, when using style object
- my state keeps adding empty elements into its array
- Wrong input validation
- Attempted import error: 'reactstrap' does not contain a default export (imported as 'Table')
- How to take as much space as they can in flex wrap
- How to refer a css file from index.html in React
- How can I use react masonry with react-infinite-scroller?
- Uncaught Error: Map container is already initialized
- Function not getting all documents in a collection
- 502 gateway error when utilizing AWS amplify, cloudwatch gives error on random line?
- ReactJS - Adding value on specific table row
- Array animation in ReactJS, TypeScript
- Creating a React CSS object with clamp and focus
- React application hosted in S3 bucket with OKTA OIDC Authorization grant with PKCE flow (AuthSdk error)
- Webpack + React + multiple SVG loaders issue
- React hook - onFocus and onBlur
- Getting an API URL id from another API data not working properly
- Gatsby client-side routes with multiple params
- Rendering a component multiple times with different props in React
- Creating a button that commits an input field's text to my state in React
- How do I route in react word web add-in?
- ReactJS - How to get access to state value inside a funciton?
- How do I render 1 of 3 SVGs inside a component using conditions in React?