Understanding .env files with ReactJS
What is a .env file?
It’s a file used to store environment variables.
An environment variable is simply a variable that can be accessed throughout the entire project.
It’s generally used to:
- Store API keys
- Remember certain URLs
- Make certain names configurable (such as the site name)
Why use a .env file?
The main benefit is that if a developer wants to modify an API key, an address, or even a name, they only need to change it in one place: the .env
file.
Without a .env
file, the developer would have to modify the API key in all the files where it’s used. This could take hours upon hours.
With this file, the information is changed in only one place, the .env
file.
Another benefit is that, by default, the .env
file is not sent to remote services such as GitHub or GitLab: the .env
file is ignored by Git.
Wait, what is Git? 👀
Git is a command-line software (used from the computer's terminal) that allows you to create multiple versions of a project.
It is an extremely important tool for any good web developer.
Want to learn Git?
In short, there’s no risk of uploading secret keys online because the file containing our information is never pushed online. This ensures adherence to security principles and avoids redundancy.
How to create a .env file?
In the root of your project, such as a React project, simply create a .env
file with no name—just this extension.
You can also create specific files depending on the context in which your project is running.
For example:
.env.development
- the file used in development.env.production
- the file used in production
How to use a .env file?
Creating a new variable
To use a .env
file, start by creating a new variable.
To do so, open the .env
file and type this:
GOOGLE_API_KEY=value
There is no need to add keywords before a variable. However, uppercase letters are used by convention.
Accessing a variable
The technique depends on whether you used Vite to create your React project or Create React App.
// With VITE
const apiKey = import.meta.env.GOOGLE_API_KEY;
// With Create React App / Next.js
const apiKey = process.env.GOOGLE_API_KEY;
Example of using a .env file
Let’s take an example of making a request.
const apiKey = import.meta.env.GOOGLE_API_KEY;
const apiUrl = import.meta.env.GOOGLE_API_URL;
const fetchData = async () => {
const response = await fetch(apiUrl, {
headers: {
"Authorization": `Bearer ${apiKey}`,
"Content-Type": "application/json"
}
});
if (response.ok) {
console.log(await response.json());
} else {
console.error(`Error: ${response.status}`);
}
};
export default fetchData;
In this small example, we use the variables GOOGLE_API_KEY
and GOOGLE_API_URL
to store:
- our API URL
- our API key
Easy, right? 👀
Conclusion
We’ve seen how to use a .env
file with React. Keep in mind that it’s very useful to use one.