techStackGuru

React dotenv


Step 1: Install the dotenv package:

npm install dotenv

Step 2: Create a .env

You will need to create a file called .env in the root directory of your project. You will find your environment variables in this file.

REACT_APP_API_KEY=your_api_key
REACT_APP_BASE_URL=http://example.com

Step 3:

Added the following import to the top of your index.js or app.js files (or any entry points):

import 'dotenv/config';

Step 4:

Create React App, by default, only exposes variables that begin with REACT_APP_, so now you can access your environment variables anywhere in your React application using process.env.

const apiKey = process.env.REACT_APP_API_KEY;
const baseUrl = process.env.REACT_APP_BASE_URL;

Example

The .env file should be created in your project's root directory. Here's a simple environment variable we can use as a demonstration:

REACT_APP_WELCOME_MESSAGE=Hello from dotenv!

In the src/index.js file, import dotenv:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import dotenv from 'dotenv';

dotenv.config(); // Load environment variables

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

In your src/App.js file, access the environment variable:

import React from 'react';

function App() {
  const welcomeMessage = process.env.REACT_APP_WELCOME_MESSAGE;

  return (
    <div>
      <h1>{welcomeMessage}</h1>
    </div>
  );
}

export default App;

Note:

  • Version Control: Do not commit sensitive .env files to version control. Make a .gitignore file to exclude it.
  • Security: Dotenv is primarily used for development convenience. If you are planning to use the platform in production, you should consider more secure mechanisms like server-side environment variables or external secret management providers.