Setup your .env files for React
Setup .env with React and Webpack
Install the necessary packages: Install the dotenv package to read variables from the .env file and dotenv-webpack package to integrate it with webpack. You can install them by running the following command:
npm install dotenv dotenv-webpack --save-dev
Create a .env file: Create a .env file at the root of your project and define the environment variables you want to use in the Redux initial state slice. For example:
REACT_APP_API_KEY=your_api_key
REACT_APP_API_URL=https://api.example.com
the REACT_APP_ prefix in the variable names. This prefix is required for Create React App (CRA) projects to automatically load the variables.
Configure webpack: In your webpack configuration file (usually named webpack.config.js), add the following code:
const Dotenv = require('dotenv-webpack');
module.exports = {
// Other webpack configuration options...
plugins: [
new Dotenv(),
],
};
This configuration tells webpack to use the dotenv-webpack plugin to load the environment variables from the .env file.
Update the Redux initial state: In your Redux slice file, import the dotenv package and use it to access the environment variables. For example:
import { createSlice } from '@reduxjs/toolkit';
import dotenv from 'dotenv';
dotenv.config();
const initialState = {
apiKey: process.env.REACT_APP_API_KEY,
apiUrl: process.env.REACT_APP_API_URL,
// Other initial state values...
};
const appSlice = createSlice({
name: 'app',
initialState,
reducers: {
// Redux reducers...
},
});
export const { actions } = appSlice;
export default appSlice.reducer;
By calling dotenv.config(), the environment variables defined in the .env file will be loaded into process.env so that you can access them.
Remember to restart your development server after creating or updating the .env file for the changes to take effect.
Now, when your Redux store is initialized, the initial state slice will be populated with the values from the .env file, and you can use them throughout your application.