npm install dotenv
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
Added the following import to the top of your index.js or app.js files (or any entry points):
import 'dotenv/config';
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;
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!
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')
);
import React from 'react';
function App() {
const welcomeMessage = process.env.REACT_APP_WELCOME_MESSAGE;
return (
<div>
<h1>{welcomeMessage}</h1>
</div>
);
}
export default App;