Prerequisite:
This tutorial assumes that you have some knowledge of Html, CSS,Tailwind CSS,Javascript, and React.
At the end of this tutorial, you should be able to create and use environmental variables in React.
Overview:
- what are environmental variables
- Reason for environmental variables
- Setting up and accessing environmental variables in create-react-app
- Setting up and accessing environmental variables in Vite
- Conclusion
What are environmental variables
Environmental variables in React are special variables that store configuration settings or sensitive information outside of your application's source code.
Environmental variables are typically stored in files named .env or .env.local at the root of your project.
Reasons for environmental variables
Environmental variables are useful for storing sensitive information like:
- API keys
- API endpoints
- Database credentials
Setting up environmental variables in create-react-app
In React,environmental variables are declared by creating a .env file in your project root folder and declaring the variable name in all uppercase,like so
REACT_APP_YOUR_VARIABLE_NAME=thisismyFirstENVvariablewithCreateReactApp
Accessing environmental variables in create-react-app
process.env.REACT_APP_YOUR_VARIABLE_NAME
import "./App.css";
import { useState } from "react";
export default function App() {
const [jokes, setJokes] = useState();
const url = "https://jokes-by-api-ninjas.p.rapidapi.com/v1/jokes?";
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": process.env.REACT_APP_API_KEY,
"X-RapidAPI-Host": "jokes-by-api-ninjas.p.rapidapi.com",
},
};
async function getJokes() {
try {
const response = await fetch(url, options);
const result = await response.text();
setJokes(result);
} catch (error) {
console.error(error);
}
}
return (
<div className='App w-full flex justify-center items-center mt-40 '>
<div className=' w-[80%] lg:w-1/3 bg-gray-500 rounded-lg py-6 space-y-6 shadow-xl '>
<p className='text-white text-lg font-semibold px-3'>{jokes}</p>
<button
className='rounded-md bg-purple-400 text-white p-2 '
onClick={() => getJokes()}
>
Get Advice
</button>
</div>
</div>
);
}
Setting up environmental variables in Vite React
Environmental variable in vite react starts with VITE_
like so
VITE_YOUR_VARIABLE_NAME=thisismyfirstENVvariableinVite
Accessing environmental variables in Vite React
import.meta.env.VITE_YOUR_VARIABLE_NAME
const options = {
method: "GET",
headers: {
"X-RapidAPI-Key": import.meta.env.VITE_API_KEY,
"X-RapidAPI-Host": "jokes-by-api-ninjas.p.rapidapi.com",
},
};
Conclusion
Environmental variables enhance security by keeping sensitive information, such as API keys or database passwords, out of source code. Storing these secrets as environmental variables helps protect them from accidental exposure and unauthorized access.
Top comments (0)