Welcome to this comprehensive guide on using Environment Variables in React JS! This tutorial is designed for both beginners and intermediates, so let's get started! š
Environment Variables are simple key-value pairs that store configuration data for your application. They can hold values like API keys, database URLs, or even user-specific settings. Using Environment Variables helps keep sensitive data out of your code, making it more secure. š” Pro Tip: Always store sensitive data like API keys in Environment Variables, never hard-code them in your code.
To work with Environment Variables in React JS, we'll use the dotenv package. If you haven't installed it yet, you can do so by running:
npm install dotenvNow, create a .env file in the root directory of your project and add your Environment Variables like this:
REACT_APP_API_KEY=my_api_key
REACT_APP_DB_URL=my_database_url
š Note: Always prefix your Environment Variables with REACT_APP to make them available at runtime.
To access the Environment Variables, you'll first need to create a .env.development, .env.test, or .env.production file, depending on your current environment. This file will contain the same variables as the .env file, but with the relevant environment-specific settings.
touch .env.developmentNow, in your React JS code, you can access the Environment Variables like this:
import React from 'react';
import dotenv from 'dotenv';
dotenv.config();
function App() {
const apiKey = process.env.REACT_APP_API_KEY;
return (
<div>
<h1>My API Key is: {apiKey}</h1>
</div>
);
}
export default App;In this example, we're importing dotenv and process.env to access the Environment Variables. The process.env.REACT_APP_API_KEY line fetches the value of the REACT_APP_API_KEY Environment Variable from the .env file.
What is the purpose of prefixing Environment Variables with `REACT_APP` in React JS?
To handle multiple environments like development, testing, and production, you'll need to set up Webpack or Create React App to read the correct .env file based on the current environment.
For this tutorial, we'll focus on the basics of using Environment Variables in React JS. If you're interested in learning more about handling multiple environments, we recommend checking out the official Create React App documentation.
That's it for our guide on using Environment Variables in React JS! By now, you should have a good understanding of what they are, why they're useful, and how to work with them in your React JS projects. Happy coding! š” Pro Tip: Don't forget to commit and store your .env files in your Git repository, but never commit the .env.local file which should contain your local development Environment Variables.
š Note: This tutorial covered the basics of using Environment Variables in React JS. If you're looking for more advanced topics like handling multiple environments or using other package managers, consider checking out the official documentation for further learning.