When building modern web applications, managing configuration through environment variables is essential. It allows developers to store sensitive information securely and differentiate between development and production settings. In this post, we’ll explore how to set up environment variables in three popular frameworks: Next.js, React (Create React App), and Vite (React).
1. Setting Up Environment Variables in Next.js
Next.js is a powerful React framework that provides built-in support for environment variables. Here’s how to configure them:
Steps to Add Environment Variables:
-
Create an
.env.local
File
In the root of your Next.js project, create a file named.env.local
. This file is used for local development and should not be committed to version control. -
Add Your Environment Variables
Use theNEXT_PUBLIC_
prefix for any variables you want to expose to the browser. Here’s an example:NEXT_PUBLIC_API_URL=https://api.example.com NEXT_PUBLIC_FIREBASE_API_KEY=AIzaSyAsKkKgONxMTXPn1GuZtXNcJBF9H5gFnig
-
Access the Variables in Your Code You can access these variables in your Next.js components or API routes like this:
const apiUrl = process.env.NEXT_PUBLIC_API_URL; const firebaseApiKey = process.env.NEXT_PUBLIC_FIREBASE_API_KEY;
-
Restart the Server After adding or modifying environment variables, restart your Next.js development server to apply the changes.
2. Adding Environment Variables in React (Create React App)
Create React App (CRA) simplifies the setup of a React project and also supports environment variables, albeit with a different naming convention.
Steps to Add Environment Variables:
-
Create a .env File In the root of your Create React App project, create a file named
.env
. -
Add Your Environment Variables Use the REACT_APP_ prefix for variables you want to expose. Here’s an example:
REACT_APP_API_URL=https://api.example.com REACT_APP_FIREBASE_API_KEY=AIzaSyAsKkKgONxMTXPn1GuZtXNcJBF9H5gFnig
-
Access the Variables in Your Code You can access these variables in your React components like this:
const apiUrl = process.env.REACT_APP_API_URL; const firebaseApiKey = process.env.REACT_APP_FIREBASE_API_KEY;
3. Using Environment Variables in Vite (React)
Vite is a fast build tool that offers an efficient way to develop React applications. Here’s how to manage environment variables in Vite.
Steps to Add Environment Variables:
-
Create a .env File In the root of your Vite project, create a file named .env.
-
Add Your Environment Variables Use the VITE_ prefix for variables you want to expose. Here’s an example:
VITE_API_URL=https://api.example.com VITE_FIREBASE_API_KEY=AIzaSyAsKkKgONxMTXPn1GuZtXNcJBF9H5gFnig
-
Access the Variables in Your Code You can access these variables in your Vite components like this:
const apiUrl = import.meta.env.VITE_API_URL; const firebaseApiKey = import.meta.env.VITE_FIREBASE_API_KEY;