#3948·orval

fetch: Up to 85% less generated code with a new fetch client generation style

Author: soartec-labCreated Aug 31, 2026Updated Sep 13, 2026
Labelsfetch

Summary

This proposal adds a new generation style for the fetch client that shares the execution logic currently duplicated into every operation. orval generates a shared runtime once per project, and each operation becomes declarative code that references it.

Impact

Generated code shrinks by roughly 70–75% in typical setups, and by up to ~85% in combined cases (multiple specs × heavy operations × tags-split).

Problem

The current fetch client writes the execution logic directly into each operation's function (inlining). This approach has benefits we have always valued:

  • the generated output is self-contained, with zero dependencies
  • reading a single function shows the entire request flow
  • version skew between the generator and the executing code is structurally impossible

On the other hand, the same execution logic, per-status type aliases, and URL builders are duplicated into every operation, producing about 50 lines of boilerplate per operation — the generated code grows with (number of operations) × (number of specs). The new style removes this duplication.

Main changes

Current style (option value: inline)

typescript
export type listPetsResponse200 = { data: Pets; status: 200 };
export type listPetsResponseDefault = { data: Error; status: Exclude<HTTPStatusCodes, 200> };
export type listPetsResponseSuccess = listPetsResponse200 & { headers: Headers };
export type listPetsResponseError = listPetsResponseDefault & { headers: Headers };
export type listPetsResponse = listPetsResponseSuccess | listPetsResponseError;

export const getListPetsUrl = (params: ListPetsParams) => {
  const normalizedParams = new URLSearchParams();
  Object.entries(params || {}).forEach(([key, value]) => {
    if (value !== undefined) {
      normalizedParams.append(key, value === null ? 'null' : String(value));
    }
  });
  const stringifiedParams = normalizedParams.toString();
  return stringifiedParams.length > 0 ? `/pets?${stringifiedParams}` : `/pets`;
};

export const listPets = async (params: ListPetsParams, options?: RequestInit): Promise<listPetsResponse> => {
  const res = await fetch(getListPetsUrl(params), { ...options, method: 'GET' });
  const body = [204, 205, 304].includes(res.status) ? null : await res.text();
  const data: listPetsResponse['data'] = body ? JSON.parse(body) : {};
  return { data, status: res.status, headers: res.headers } as listPetsResponse;
};

New style (option value: shared)

Three kinds of files are generated:

  • Operation files (existing, contents change) — one operation = "types + URL builder + thin wrapper", about 10 lines.
  • client-config.ts (new, only for specs using a mutator) — a config file passed to the runtime.
  • runtime.ts (new) — execution logic and common types. Generated once per project and shared by all operation files.

Operation files

typescript
// pets.ts
import { execute, serializeQuery } from '../runtime';
import type { CallOptions, ResponseOf } from '../runtime';

// Derives the actual response union from the spec's responses map (status → type).
// Both the name and the structure are fully compatible with what inline exports
export type listPetsResponse = ResponseOf<{ 200: Pets; default: Error }>;

// URL builders keep the same shape as inline; only the heavy query
// serialization is delegated to the shared runtime
export const getListPetsUrl = (params?: ListPetsParams) => {
  const q = serializeQuery(params, { explode: ['tags'] });
  return q ? `/pets?${q}` : `/pets`;
};

export const listPets = (params?: ListPetsParams, options?: CallOptions) =>
  execute<listPetsResponse>({ url: getListPetsUrl(params), method: 'GET', options });

Path-only URL builders are identical to inline:

typescript
export const getShowPetByIdUrl = (petId: string) => {
  return `/pets/${petId}`;
};

export const showPetById = (petId: string, options?: CallOptions) =>
  execute<showPetByIdResponse>({ url: getShowPetByIdUrl(petId), method: 'GET', options });

client-config.ts (only for specs using a mutator)

Generated only for specs where override.mutator is configured; it connects the mutator to the runtime.

typescript
// client-config.ts
import * as runtime from './runtime';
import type { ExecuteArgs } from './runtime';
import { customFetch } from '../custom-fetch';

const config = { mutator: customFetch };

export const execute = <R,>(args: ExecuteArgs) => runtime.execute<R>(args, config);

runtime.ts

The execution body currently inlined into every operation (the fetch call, empty-body handling, decoding, header merging), the query serialization, and the common types are generated here exactly once. The public API is just two functions — execute and serializeQuery — plus a few common types (ResponseOf, StatusOf, etc.).

The per-status type aliases that inline exports (listPetsResponse200, etc.) are no longer generated; instead, StatusOf provides access by status code:

typescript
type NotFoundBody = StatusOf<listPetsResponse, 404>['data'];

Details

Configuration

Three new options under override.fetch:

typescript
override: {
  fetch: {
    // 'inline' (default, current behavior) | 'shared'
    runtimeImplementationStyle: 'shared',
    // optional: where the shared runtime is generated (default: runtime.ts next to the target)
    runtimeOutputPath: './src/runtime.ts',
    // optional: where the spec config file is generated (default: client-config.ts next to the target)
    clientConfigOutputPath: './src/petstore-client/client-config.ts',
  },
},

Compatibility

  • Applies to client: 'fetch', and to the internal fetchers of the query wrappers (react-query / swr / vue-query) when using output.httpClient: 'fetch'.
  • Behavior and call signatures are exactly identical to the current generated code (including the response shape with status narrowing, empty-body handling, and byte-identical query serialization). Switching styles produces zero diff in app code and test code.
  • Mutators (customFetch) and MSW keep working without any modification.
  • Some options (forceSuccessResponse / jsonReviver / runtimeValidation, etc.) will be supported incrementally.
  • The default stays inline (the current style).

Development plan

  • Add the config options (runtimeImplementationStyle / runtimeOutputPath / clientConfigOutputPath)
  • Implement the shared runtime (runtime.ts)
  • Generate the shared style for the fetch client (types / URL builders / wrappers / client-config.ts)
  • Sample app
  • Support the query wrappers (httpClient: 'fetch')
  • Documentation

We plan to consider shipping the stabilized release of all of this together with a major upgrade to orval v9.