Article

Typed TypeScript SDKs from OpenAPI with Orval: one package per service

Generate a typed fetch SDK per service from OpenAPI with Orval. Unwrap the envelope, return errors as values, pin the types and publish per release.

Published Updated 8 min read

This guide is for frontend architects and tech leads whose channels, such as a web store and an app, call the same API layer. It shows how to generate typed TypeScript SDKs from OpenAPI specs with Orval, so that each service gets its own npm package. The functions use plain fetch, never throw, and return { data, error, meta }. The examples use orval 8.51.0, typescript 7.0.2, expect-type 1.4.0 and tsdown 0.23.7, which are the current npm versions on 1 December 2026.

Install the tools in the folder that holds the generator:

npm install --save-dev orval typescript expect-type tsdown

One package per service

A single SDK for all services ties their releases together, while one package per service keeps them apart:

  • A channel installs only the services that it calls.
  • The package version is the service version, so a checkout release does not change the catalog package.
  • Orval’s fetch functions have no runtime dependencies, and because each operation is a separate export, a bundler removes the operations that a channel does not import.

The examples use this layout:

sdk/
  orval.config.ts
  runtime/fetch.ts          # custom fetch, result type, error type
  specs/catalog.json        # exported OpenAPI specs
  packages/catalog/         # one package per service
    package.json
    tsdown.config.ts
    src/index.ts
    src/generated/          # written by Orval
  type-tests/
    tsconfig.base.json
    catalog/tsconfig.json
    catalog/api.test-d.ts
  scripts/build-sdk.sh

Configure Orval

Create one Orval project per service and use the service name as the project name.

// orval.config.ts
import { defineConfig } from 'orval';

const services = ['catalog', 'checkout', 'account'];

export default defineConfig(
  Object.fromEntries(
    services.map((service) => [
      service,
      {
        input: { target: `./specs/${service}.json` },
        output: {
          target: `./packages/${service}/src/generated/${service}.ts`,
          mode: 'split',
          client: 'fetch',
          clean: true,
          override: {
            mutator: {
              path: './runtime/fetch.ts',
              name: 'customFetch',
              inferred: true,
            },
          },
        },
      },
    ]),
  ),
);

What the options do:

  • client: 'fetch' generates functions that call the Fetch API, so you need no HTTP library.
  • mode: 'split' writes the operations and the schema types to two files.
  • clean: true empties the output folder first, so an endpoint that you remove from the spec also leaves the SDK.
  • override.mutator sends every request through your own function, customFetch.
  • inferred: true makes the generated functions take their return type from the mutator. Without it, Orval declares its own response type with data, status and headers.

Generate one service with the --project flag:

npx orval --config ./orval.config.ts --project catalog

A generated operation looks like this (formatted):

export const getProduct = (
  productId: string,
  params: GetProductParams,
  options?: Parameters<typeof customFetch>[1],
) => {
  return customFetch<getProductResponse>(getGetProductUrl(productId, params), {
    ...options,
    method: 'GET',
  });
};

getProductResponse is a union with one member per status code in the spec, for example { data: ProductResponse; status: 200 } and { data: ErrorResponse; status: 422 }, and the mutator reads the success type from this union.

Check the operationIds first

Orval names each function after the operationId in the spec. FastAPI, for example, builds a default operationId from the handler name, the path and the method: get_products_catalog_v2_products_get. Shorten these names before you generate, for example to getProductsV2, and let the build fail when two operations get the same name. From then on, a renamed handler also renames an SDK function, so treat that as a breaking change.

Return a result instead of throwing

Channels handle errors in different ways: a server component renders a fallback, while an app screen shows a retry button. With a result type, every caller must handle the error, and TypeScript checks that it does.

// runtime/fetch.ts (part 1)
export type ApiErrorKind = 'http' | 'network' | 'aborted' | 'empty' | 'parse';

export interface ApiError {
  kind: ApiErrorKind;
  status: number; // 0 when no response arrived
  message: string;
  details: unknown[];
  code?: string;
  traceId?: string;
  body?: unknown;
  cause?: unknown;
}

export type Result<TData, TMeta> =
  | { data: TData; meta: TMeta; error: null; status: number; headers: Headers }
  | { data: null; meta: TMeta | null; error: ApiError; status: number; headers: Headers | null };

A caller checks error first, and after that check TypeScript knows that data is not null:

const { data, error } = await getProduct('p-1', { locale: 'en-GB' });
if (error) {
  return renderFallback(error.kind);
}
return renderProduct(data.name);

One error type covers every failure:

kind When
http A non-2xx status, or a 2xx envelope that contains an error
network No response, for example after a DNS or connection error
aborted The request signal aborted, for example after a timeout
empty A 2xx response without a body, other than 204 or 205
parse A 2xx response with invalid JSON

Validation errors (400 or 422) put the field errors in details. When a gateway returns an HTML error page, you get kind: 'http', the message HTTP 502 and the raw HTML in body, so your logger can store the page and the UI does not parse it.

Write the custom fetch function

The mutator builds the request, catches network errors, unwraps the envelope and maps every failure to ApiError. The examples assume an envelope of { data, error, meta }, so change the field names to match your API.

Unwrap the envelope in the types

Four helper types turn Orval’s response union into the result type:

// runtime/fetch.ts (part 2)
type SuccessStatus = 200 | 201 | 202 | 203 | 204 | 206;
type SuccessBody<T> = T extends { status: SuccessStatus; data: infer D } ? D : never;
type EnvelopeData<B> = B extends { data: infer D } ? D : B;
type EnvelopeMeta<B> = B extends { meta: infer M } ? M : null;

SuccessBody keeps the body of the 2xx members, and EnvelopeData and EnvelopeMeta take data and meta out of that body. For getProduct, the return type is then Promise<Result<Product, Meta>>.

One configuration per channel

Each channel calls configure once. The web store sets a base URL, an API key and a logger on the server, while the app sets its own base URL and headers.

// runtime/fetch.ts (part 3)
export interface FetchConfig {
  baseUrl: string | (() => string);
  apiKey?: string;
  headers?: Record<string, string> | (() => Promise<Record<string, string>>);
  fetch?: typeof globalThis.fetch;
  onError?: (error: ApiError, request: { method: string; url: string }) => void;
}

let config: FetchConfig = { baseUrl: '' };

export function configure(options: Partial<FetchConfig>): void {
  config = { ...config, ...options };
}

The fetch function

// runtime/fetch.ts (part 4)
export async function customFetch<T extends { status: number; data: unknown }>(
  url: string,
  init: RequestInit = {},
): Promise<Result<EnvelopeData<SuccessBody<T>>, EnvelopeMeta<SuccessBody<T>>>> {
  type Out = Result<EnvelopeData<SuccessBody<T>>, EnvelopeMeta<SuccessBody<T>>>;
  const method = init.method ?? 'GET';
  const base = typeof config.baseUrl === 'function' ? config.baseUrl() : config.baseUrl;
  const fullUrl = base + url;

  // Later sources win: defaults, API key, channel headers, per-call headers
  const headers = new Headers({ accept: 'application/json' });
  if (config.apiKey) headers.set('x-api-key', config.apiKey);
  const extra = typeof config.headers === 'function' ? await config.headers() : config.headers;
  for (const [key, value] of Object.entries(extra ?? {})) headers.set(key, value);
  new Headers(init.headers).forEach((value, key) => headers.set(key, value));

  const fail = (error: ApiError, res?: Response, meta: unknown = null): Out => {
    config.onError?.(error, { method, url: fullUrl });
    return { data: null, meta: meta as Out['meta'], error, status: error.status, headers: res?.headers ?? null };
  };

  let res: Response;
  let text: string;
  try {
    res = await (config.fetch ?? globalThis.fetch)(fullUrl, { ...init, headers });
    text = await res.text();
  } catch (cause) {
    const aborted =
      init.signal?.aborted ||
      (cause instanceof DOMException && ['AbortError', 'TimeoutError'].includes(cause.name));
    return fail({ kind: aborted ? 'aborted' : 'network', status: 0, message: String(cause), details: [], cause });
  }

  if (!text) {
    if (res.status === 204 || res.status === 205) {
      return { data: null, meta: null, error: null, status: res.status, headers: res.headers } as Out;
    }
    const kind = res.ok ? 'empty' : 'http';
    return fail({ kind, status: res.status, message: `HTTP ${res.status}`, details: [] }, res);
  }

  let body: any;
  try {
    body = JSON.parse(text);
  } catch (cause) {
    // A gateway error page is HTML: keep the raw text for logging
    const kind = res.ok ? 'parse' : 'http';
    return fail({ kind, status: res.status, message: `HTTP ${res.status}`, details: [], body: text, cause }, res);
  }

  const isEnvelope = typeof body === 'object' && body !== null && ('data' in body || 'error' in body);
  if (!res.ok || (isEnvelope && body.error)) {
    const err = (isEnvelope && body.error) || {};
    return fail(
      {
        kind: 'http',
        status: res.status,
        message: err.message ?? `HTTP ${res.status}`,
        details: Array.isArray(err.details) ? err.details : [],
        code: err.code,
        traceId: body?.meta?.traceId,
        body,
      },
      res,
      isEnvelope ? (body.meta ?? null) : null,
    );
  }

  return {
    data: isEnvelope ? (body.data ?? null) : body,
    meta: isEnvelope ? (body.meta ?? null) : null,
    error: null,
    status: res.status,
    headers: res.headers,
  } as Out;
}

Some details:

  • The function reads config.fetch on every request, so a test can replace it with a stub.
  • A body without an envelope comes back as data, with meta: null.
  • onError sees every error, so you can send it to your logger along with the trace ID when the API returns one.

Use it in a channel

// web store: lib/catalog.server.ts
import 'server-only';
import { configure, getProduct } from '@your-org/catalog-sdk';

configure({
  baseUrl: process.env.API_BASE_URL ?? '',
  apiKey: process.env.API_KEY,
  onError: (error, request) => {
    console.error('API error', request.method, request.url, error.kind, error.status, error.traceId);
  },
});

export const loadProduct = (id: string, locale: string) =>
  getProduct(id, { locale }, { next: { revalidate: 300 }, signal: AbortSignal.timeout(5000) });

In Next.js, import 'server-only' gives a build error when a Client Component imports the module, which keeps the API key out of the browser bundle. Next.js reads next.revalidate from the fetch options, and the mutator passes those options on. A timeout from AbortSignal.timeout returns kind: 'aborted'. Every package has its own configure, because the build copies the runtime into each package.

Pin the public API with type tests

The generated code changes when the spec changes. A type test turns an unplanned change in the public API into a failed build, and it also shows how to call the SDK.

The test imports the package by its name, and a paths entry maps that name to the built .d.mts file, so the test checks the types that you publish. Put this in type-tests/tsconfig.base.json:

{
  "compilerOptions": {
    "strict": true,
    "noEmit": true,
    "target": "es2022",
    "module": "esnext",
    "moduleResolution": "bundler",
    "lib": ["es2022", "dom"],
    "paths": {
      "@your-org/*-sdk": ["../packages/*/dist/index.d.mts"]
    }
  }
}

Each service has a one-line tsconfig.json in its own folder:

{ "extends": "../tsconfig.base.json", "include": ["*.ts"] }

This is the test for the catalog service:

// type-tests/catalog/api.test-d.ts
import { expectTypeOf } from 'expect-type';
import { getProduct, listProducts, type Product, type Meta, type Result } from '@your-org/catalog-sdk';

// Pin the return types
expectTypeOf(getProduct).returns.resolves.toEqualTypeOf<Result<Product, Meta>>();
expectTypeOf(listProducts).returns.resolves.toEqualTypeOf<Result<Product[], Meta>>();

// Show how a channel uses the result
async function example() {
  const { data, error } = await getProduct('p-1', { locale: 'en-GB' });
  if (error) {
    expectTypeOf(data).toBeNull();
    expectTypeOf(error.kind).toEqualTypeOf<'http' | 'network' | 'aborted' | 'empty' | 'parse'>();
    return;
  }
  expectTypeOf(data).toEqualTypeOf<Product>();
}

// Calls that must not compile
// @ts-expect-error locale is required
getProduct('p-1', {});
// @ts-expect-error unknown query parameter
listProducts({ locale: 'en-GB', sort: 'name' });
// @ts-expect-error productId is a string
getProduct(42, { locale: 'en-GB' });

Run it with the compiler:

npx tsc -p type-tests/catalog

The test never runs, because the compiler only checks it. @ts-expect-error fails the check when the next line compiles, so the test also catches types that are too loose. When getProduct returns another type, toEqualTypeOf fails.

You can use tsd (0.33.0) instead of expect-type, or, without a library, a satisfies expression or a small Equal helper type. Note that satisfies checks that a value fits a type, but it does not check that the types are equal.

Build one package per service

Each package folder has three small files, which the generator can write from a template.

// packages/catalog/src/index.ts
export * from './generated/catalog';
export * from './generated/catalog.schemas';
export { configure, type ApiError, type Result } from '../../../runtime/fetch';
// packages/catalog/tsdown.config.ts
import { defineConfig } from 'tsdown';

export default defineConfig({
  entry: ['src/index.ts'],
  format: ['esm', 'cjs'],
  dts: true,
  platform: 'neutral',
  fixedExtension: true,
});

And packages/catalog/package.json:

{
  "name": "@your-org/catalog-sdk",
  "version": "0.0.0",
  "type": "module",
  "sideEffects": false,
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    }
  },
  "files": ["dist"]
}

tsdown bundles the runtime into each package, so the packages do not depend on each other. platform: 'neutral' makes no runtime assumptions, which fits a library that runs on a Next.js server, in the browser and in a React Native app. fixedExtension: true always writes .mjs and .cjs files.

One script builds, tests and packs a service:

#!/usr/bin/env bash
# Usage: scripts/build-sdk.sh <service> [version]
set -euo pipefail

SERVICE="$1"
VERSION="${2:-$(node -p "require('./specs/$SERVICE.json').info.version")}"
PKG="packages/$SERVICE"

if [[ ! -f "type-tests/$SERVICE/tsconfig.json" ]]; then
  echo "No type test for $SERVICE" >&2
  exit 1
fi

npx orval --config ./orval.config.ts --project "$SERVICE"
(cd "$PKG" && npm pkg set version="$VERSION" && npx tsdown)

# Type tests run against the built .d.mts files
npx tsc -p "type-tests/$SERVICE"

# Both builds must load
node --input-type=module -e "await import('./$PKG/dist/index.mjs')"
node --input-type=commonjs -e "require('./$PKG/dist/index.cjs')"

npm pack "./$PKG"

The version comes from info.version in the spec unless you pass one. The script stops when a service has no type test, and the type tests run after the build and before npm pack. With TypeScript 7.0.2, tsdown 0.23.7 prints a deprecation warning for its declaration generator, but the build still completes.

Publish with the same version as the service

The release pipeline of a service calls a reusable workflow and passes it the service name and the release version.

# .github/workflows/publish-sdk.yml
name: Publish SDK

on:
  workflow_call:
    inputs:
      service:
        type: string
        required: true
      version:
        type: string
        required: true
  workflow_dispatch:
    inputs:
      service:
        type: string
        required: true
      version:
        type: string
        required: true

permissions:
  contents: read
  packages: write

jobs:
  publish:
    runs-on: ubuntu-latest
    env:
      SERVICE: ${{ inputs.service }}
      VERSION: ${{ inputs.version }}
    steps:
      - name: Check the version format
        run: |
          if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
            echo "Expected X.Y.Z, got $VERSION"
            exit 1
          fi

      - uses: actions/checkout@v7
        with:
          ref: ${{ inputs.service }}-v${{ inputs.version }}

      - uses: actions/setup-node@v7
        with:
          node-version: '24'
          registry-url: 'https://npm.pkg.github.com'
          scope: '@your-org'
          package-manager-cache: false

      - name: Export the spec
        run: ./scripts/export-openapi.sh "$SERVICE" > "sdk/specs/$SERVICE.json"

      - name: Build and test the SDK
        working-directory: sdk
        run: |
          npm ci
          ./scripts/build-sdk.sh "$SERVICE" "$VERSION"

      - name: Publish
        working-directory: sdk
        run: npm publish "your-org-$SERVICE-sdk-$VERSION.tgz"
        env:
          NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

The release workflow of the service calls it after the release job:

  publish-sdk:
    needs: release
    permissions:
      contents: read
      packages: write
    uses: ./.github/workflows/publish-sdk.yml
    with:
      service: catalog
      version: ${{ needs.release.outputs.version }}

How it works:

  • The format check stops versions such as 1.4 or 1.4.0-rc.1.
  • The checkout uses the release tag, so the spec matches the released code.
  • The export step depends on your framework: a FastAPI app, for example, can write the result of app.openapi() to a file.
  • With scope, only @your-org packages use the private registry, while other packages still come from the public registry.
  • The calling job grants packages: write, because a called workflow can keep or reduce the GITHUB_TOKEN permissions but cannot raise them.
  • npm refuses a name and version that already exist, so a rerun cannot overwrite a published SDK.
  • workflow_dispatch lets you publish a missed release by hand.

For packages on npmjs.com, you can use trusted publishing instead of a token, which needs id-token: write and npm CLI 11.5.1 or later.

In practice

An international cosmetics retailer sells through its web store, its app and its own stores. An API layer sits between the back-end systems and the channels, such as the web store and the app, and each service in that layer has an OpenAPI spec.

We worked in the client’s architecture team, where we wrote the proposal in October 2026. It asked for one package per service, a version tied to the spec, a custom fetch function per channel, and generation in the API repository. In November 2026, we built the generator: Orval turns each spec into plain fetch functions and types, and a build step then makes one package per service. The generator covers 8 services, such as catalog, checkout and account, and the services themselves did not change.

The SDK functions never throw. Instead, they unwrap the response envelope and return data, an error and metadata, with validation, gateway and network errors all mapped to one error type. Before Orval runs, the generator shortens long operationIds and stops on duplicate names. Each service has a type test that pins its public API and shows how to use the SDK. When a service is released, the pipeline exports its spec and publishes the SDK with the same version number. Read the full case study.

Checklist

  • Each service has its own Orval project with client: 'fetch' and clean: true.
  • Every spec has short, unique operationIds.
  • The mutator uses inferred: true, so the functions return your result type.
  • Functions return { data, error, meta } and never throw.
  • One ApiError type covers all failures, with a kind for each.
  • Gateway error pages stay in error.body as raw text.
  • Each channel calls configure once, and server secrets stay in a server-only module.
  • Each service has one type test, checked against the built .d.mts files.
  • The build stops when a service has no type test.
  • The SDK version is the service version, and the publish job checks out the release tag.

For a review of your packages, builds and shared code, see the design system and monorepo audit.

Sources

Let's connect

Talk about your project

Tell us about your team and your problem. In 30 minutes we find out whether one of our offers fits, and if none does, we tell you.

Book a 30-minute call