Environment Variables for API URLs
1. Introduction to Environment Variables
Environment variables allow us to configure application settings without hardcoding them throughout our React components. For example, an application may use one API URL during development and a different API URL in production.
Instead of repeating the API URL in every component, we can store the base URL in an environment variable and reuse it wherever API requests are required.
VITE_ prefix.
2. Why Use Environment Variables?
- Avoid repeating API URLs in multiple files.
- Switch API endpoints between development and production.
- Make application configuration easier to maintain.
- Keep environment-specific settings outside component logic.
- Reduce code changes when the API server address changes.
3. Creating an Environment Variable
In a Vite React project, create a file named
.env in the project root, where
package.json is located.
VITE_API_BASE_URL=https://jsonplaceholder.typicode.com
This variable stores the base URL of the API. We can now use it in our React application instead of hardcoding the complete URL in every request.
VITE_ prefix to be exposed through
import.meta.env in a Vite application.
4. Accessing Environment Variables
Vite provides environment variables through
import.meta.env. We can read our configured API URL
using the following code.
const API_BASE_URL =
import.meta.env.VITE_API_BASE_URL;
console.log(API_BASE_URL);
Expected output:
https://jsonplaceholder.typicode.com
.env file, restart the Vite development server
so the updated configuration is loaded.
5. Using Environment Variables in API Requests
We can combine the base URL with an API endpoint to fetch data. This makes it easier to update the API server address in one place.
const API_BASE_URL =
import.meta.env.VITE_API_BASE_URL;
export async function getUsers() {
if (!API_BASE_URL) {
throw new Error(
"API base URL is not configured."
);
}
const response = await fetch(
`${API_BASE_URL}/users`
);
if (!response.ok) {
throw new Error(
`Failed to fetch users: ${response.status}`
);
}
return response.json();
}
Here, getUsers() uses the configured base URL
and adds the /users endpoint to create the
complete request URL.
6. Displaying API Data in a React Component
Now we can import the API service into a component and display the users with loading and error states.
import { useEffect, useState } from "react";
import { getUsers } from "../services/api";
function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
async function loadUsers() {
try {
const data = await getUsers();
setUsers(data);
} catch (err) {
setError(
err instanceof Error
? err.message
: "Unable to load users."
);
} finally {
setLoading(false);
}
}
loadUsers();
}, []);
if (loading) {
return <p>Loading users...</p>;
}
if (error) {
return (
<p role="alert">
Error: {error}
</p>
);
}
return (
<div>
<h2>User List</h2>
{users.length === 0 ? (
<p>No users found.</p>
) : (
<ul>
{users.map((user) => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
)}
</div>
);
}
export default Users;
7. Different Environment Files
Vite supports different environment files for different environments. For example, you can configure separate API URLs for development and production.
VITE_API_BASE_URL=http://localhost:5000/api
VITE_API_BASE_URL=https://api.example.com
Vite loads the appropriate environment-specific configuration according to the selected mode. Replace these example URLs with the actual endpoints used by your application.
8. Environment Variables: Best Practices
- Use meaningful names such as
VITE_API_BASE_URL. - Keep environment files in the project root.
- Use different configuration values for development and production.
- Add local secret-containing environment files to
.gitignorewhen appropriate. - Provide an example configuration file for other developers.
- Restart the development server after changing environment variables.
- Validate required configuration before sending API requests.
VITE_ variables. Keep secrets
on the backend.
9. Common Problems and Solutions
| Problem | Possible Solution |
|---|---|
| Variable is undefined | Check the VITE_ prefix and variable name. |
| Old API URL is still used | Restart the Vite development server. |
| API request fails | Check the URL, server status, CORS configuration and network connection. |
| Secret appears in frontend code | Remove it from client-side configuration and move it to the backend. |
| Production uses the wrong URL | Verify the production environment configuration and build mode. |
10. Practice Tasks
- Create a Vite React project and add a
.envfile. - Configure
VITE_API_BASE_URL. - Read the variable using
import.meta.env. - Create an API service file and fetch users.
- Display the API response in a React component.
- Create development and production environment configurations.
- Test what happens when the API URL is missing or incorrect.
Summary
Environment variables help React applications manage configuration such as API base URLs across development and production environments. In Vite, variables prefixed with VITE_ can be accessed through import.meta.env. Keeping API configuration separate from component logic improves maintainability, while sensitive credentials must remain on the backend.