How to Configure Axios Using Environment Variables
Configuring the Axios HTTP client with environment variables allows you to dynamically set configuration options—such as the API base URL, timeout durations, and authentication tokens—across different deployment environments (development, staging, and production). This guide explains how to define your variables, access them across different JavaScript runtimes, and create a centralized, pre-configured Axios instance.
1. Define Environment Variables
Create a .env file in the root directory of your project
to define your configuration parameters. The prefix required for your
variable names depends on the runtime or framework you are using:
- Node.js / Express: Standard naming (e.g.,
API_BASE_URL) - Vite: Must start with
VITE_(e.g.,VITE_API_BASE_URL) - Create React App: Must start with
REACT_APP_(e.g.,REACT_APP_API_BASE_URL) - Next.js (Client-side): Must start with
NEXT_PUBLIC_(e.g.,NEXT_PUBLIC_API_BASE_URL)
Example .env file:
# Node.js example
API_BASE_URL=https://api.example.com/v1
API_TIMEOUT=5000
# Vite example
VITE_API_BASE_URL=https://api.example.com/v1
VITE_API_TIMEOUT=5000
2. Access Environment Variables in Your Code
Different environments expose these variables differently:
- In Node.js, Next.js, and
Create React App, access variables through the
process.envobject:const baseURL = process.env.API_BASE_URL || process.env.REACT_APP_API_BASE_URL; const timeout = Number(process.env.API_TIMEOUT) || 10000; - In Vite, access variables using
import.meta.env:const baseURL = import.meta.env.VITE_API_BASE_URL; const timeout = Number(import.meta.env.VITE_API_TIMEOUT) || 10000;
3. Create a Custom Axios Instance
Instead of modifying the global axios object,
instantiate a dedicated client using axios.create(). This
encapsulates your base configuration and ensures consistency throughout
the application.
Create an apiClient.js (or apiClient.ts)
file:
import axios from 'axios';
// Resolve environment variables with fallback values
const baseURL = process.env.API_BASE_URL || 'https://api.dev.example.com';
const timeout = Number(process.env.API_TIMEOUT) || 5000;
const apiClient = axios.create({
baseURL: baseURL,
timeout: timeout,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
export default apiClient;4. Use the Configured Client
Import the configured instance across your application to execute HTTP requests without repeatedly specifying the base URL or global headers:
import apiClient from './apiClient';
export async function fetchUsers() {
try {
const response = await apiClient.get('/users');
return response.data;
} catch (error) {
console.error('Failed to fetch users:', error);
throw error;
}
}