Skip to content

Pass AxiosInstance to createClient instead of AxiosStatic #2374

@idbenami

Description

@idbenami

Description

Currently, the createClient function expects the AxiosStatic type for its axios option. This forces users to pass the global axios import.

This approach prevents the use of a pre-configured AxiosInstance created with axios.create(), It's very common practice to create a single, customized Axios instance.

By not allowing an AxiosInstance to be passed, developers cannot reuse their existing, centrally-configured instance, leading to duplicated logic and a less modular setup.

Proposed Solution

I propose updating the type signature of the axios parameter in the createClient options from just AxiosStatic to AxiosStatic | AxiosInstance.

This enhancement would allow developers to inject a fully configured Axios instance, which aligns better with modern development patterns and the flexibility offered by Axios itself.

Example of Desired Usage

Here's how developers could benefit from this change:

import axios, { type AxiosInstance } from 'axios';
import { createClient } from 'hey-api';

// 1. A user creates and configures a custom Axios instance
const myApiInstance: AxiosInstance = axios.create({
  baseURL: 'https://api.example.com/v1',
  headers: { 'Authorization': `Bearer ${process.env.API_TOKEN}` },
});

// They can also attach powerful interceptors
myApiInstance.interceptors.response.use(
  (response) => {
    // Handle successful responses globally
    return response;
  },
  (error) => {
    // Handle API errors globally (e.g., refresh token on 401)
    return Promise.reject(error);
  }
);

// 2. The user passes this pre-configured instance to hey-api
const apiClient = createClient({
  axios: myApiInstance, // Pass the instance directly
  // ... other hey-api options
});

// Now all API calls made via `apiClient` will automatically use the baseURL,
// headers, and interceptors defined in `myApiInstance`.

Reproducible example or configuration

https://stackblitz.com/edit/hey-api-client-fetch-example

OpenAPI specification (optional)

No response

System information (optional)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug 🔥Something isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions