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:

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:

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;
  }
}