#3265·orval

Fetch client: Support fetch function injection

Author: jkufnerCreated Apr 22, 2026Updated Sep 9, 2026
Labelsfetch

Description

Just like #2848, the fetch client should also support dependency injection.

I would like to inject the generated APIs with a fetch function that adds authentication headers and sets base URL for the API at runtime. Something like the following function in a factory class that provides the rest of the application with the API:

typescript
const customFetch = (url, options) => {
  return fetch(new URL(url, this.appConfig.getApiBaseUrl()), {...options, ...this.authenticator.getAuthHeaders()});
}

Current behavior

The generated API is a collection of plain functions that call fetch() directly. Recently, we got a parameter to replace the fetch function; however, this still means that every API call needs to receive this new function:

typescript
import {getSomething} from "./api";
const data = getSomething({name}, addAuthHeaders({...options}), fetchFnWithBaseDir);

The currently generated API:

typescript
export const getSomething = async ( options?: RequestInit, fetchFn?: typeof globalThis.fetch): Promise<getSomethingResponseSuccess> => {
    const res = await (fetchFn ?? fetch)(getGetSomethingUrl(),
    // ...
}

Proposed behavior

Generate factory functions that accept the fetch function as a parameter, allowing runtime dependency injection:

typescript
export const createSomethingApi(fetchFn?: typeof globalThis.fetch) => ({
    getSomething: async ( options?: RequestInit ): Promise<getSomethingResponseSuccess> => {
        const res = await (fetchFn ?? fetch)(getGetSomethingUrl(),
        // ... no changes in the function body
    },
});

Then the usage of the API is much easier:

typescript
// Prepare the API
const api = createSomethingApi(customFetch);

// ... and everywhere else it is just:
const data = await api.getSomething(name);

Proposed solution

There shall be the same option for the fetch client just like the one #2848 introduced: httpClientInjection: 'factory'

The change is only how the fetchFn is provided to the generated functions -- a closure (factory) instead of the parameter.