Skip to main content
← Guides

Guide

Orval vs Hey API for TanStack Query

Updated PkgPulse Team6 min read
0

Compare Orval vs Hey API on the same OpenAPI spec. See how generated TanStack Query clients handle cache keys, mutation errors, and schema changes in CI.

Contents

Choose Orval if you want generated React hooks and already manage cache keys around request URLs. Choose Hey API if your app composes TanStack Query options in components and loaders and you can keep OpenAPI operation names stable. Keep either incumbent if its generated keys and error handling already fit your app. Before switching, run a filtered list and a rejected write through both clients.

Quick decision

What your app needsOrval with FetchHey API with Fetch
Use the same query in a component and a loaderUse the generated useListWidgets hook in React or call getListWidgetsQueryOptions from a loader.Pass listWidgetsOptions to TanStack’s own useQuery or the loader’s QueryClient.
Invalidate a filtered listThe generated key starts with the request URL without search parameters. The filters follow as an object.The generated key holds the operation ID, base URL, and filters inside an object.
Handle a duplicate-name writeIn the baseline output, the mutation resolves with the HTTP status and body. Check the status in the callback or configure Fetch to throw.The generated mutation options throw the API error body. The success callback receives the decoded record.
Review a response field added to the specIn single-file mode the type change lands beside the generated hook and request code.In this setup the change lands in the generated types file.

These results come from generating both clients from the same inventory spec. It defines a filtered GET /widgets and a POST /widgets that can reject a duplicate name. The Orval React Query guide and the Hey API TanStack Query plugin docs cover the available generator options.

What the query keys mean for invalidation

With the active filter, the generated key factories produced these values:

Orval:   ["https://inventory.example/widgets", {"state":"active"}]
Hey API: [{"_id":"listWidgets","baseUrl":"https://inventory.example","query":{"state":"active"}}]

Pass the filtered key with exact: true to invalidate the active list alone. To invalidate every filter variant for this list, call the generator’s key helper without filters and pass the result to invalidateQueries without exact. In the fixture, Orval’s URL matched both lists by array prefix. Hey API’s object matched both by operation ID and base URL. The same call left the Hey API entry for a different base URL untouched. Its isInvalidated flag stayed false. TanStack Query invalidation docs.

Build your invalidation filters from getListWidgetsQueryKey or listWidgetsQueryKey so they track what the generated client actually caches. If a loader and a component share a query, give them the same generator options and check that the resulting keys match. During a switch, check saved or hydrated entries too. A key written by the old client will need to match the new factory before the new client can read it under that key.

A rejected write can reach a different callback

Orval generated useCreateWidget and getCreateWidgetMutationOptions, with a mutation key of ['createWidget']. The mutation takes { data: { name } }. Hey API generated createWidgetMutation() for TanStack’s useMutation. It takes { body: { name } } and leaves the mutation key to the caller in this configuration. Both sent the same JSON body.

A successful create returned the record inside Orval’s { data, status, headers } envelope. Hey API’s mutation resolved to the record itself. When the fixture returned HTTP 409, Orval’s baseline mutation resolved with status: 409 and TanStack called onSuccess. The Hey API helper set throwOnError: true, rejected with the decoded error body and called onError. A test that only submits valid data would miss that difference.

With Orval’s baseline Fetch output, inspect status before you show a success message or invalidate a list. If your app expects HTTP errors in onError, Orval’s override.fetch.forceSuccessResponse: true is another option. In a separate run we enabled it and the same conflict reached onError as an Error with the HTTP status in status and the parsed body in info. Check the error shape consumed by your form before switching. Orval Fetch configuration.

Creating a widget did not automatically invalidate the cached lists. Decide whether the record can appear under multiple filters, then use the appropriate key from your success handler. If the handler returns the promise from invalidateQueries, TanStack can keep the mutation pending while the invalidation completes. Invalidation from mutations.

Regenerate after a schema edit and an operation rename

An unchanged spec produced byte-identical output on a second run. Adding optional label to the Widget response changed the Orval interface in inventory.ts and the Hey API type in types.gen.ts. The generated query and mutation functions kept their signatures in both runs.

Renaming listWidgets to findWidgets while keeping the HTTP path and parameters changed the function names for both generators. It also changed Hey API’s default _id from listWidgets to findWidgets. Orval’s key stayed equal because the URL and filters stayed equal. If your spec producer routinely renames operations, review the public imports with either tool and check cache identity with Hey API. A single-file diff can be convenient for a small spec. Separate generated types make a field-only diff easier to find when you review it.

Pin the generator and lockfile, then regenerate from the same spec in CI. If you commit generated code, check for new and removed files as well as changes to tracked files. Assert the exact list key and which callback a rejected write reaches. A clean regeneration diff can tell you whether the output drifted. Those assertions tell you whether the generated behavior still fits your app.

Methodology

We used Orval 8.51.0, @hey-api/openapi-ts 0.99.0, and @tanstack/react-query 5.108.4. Node.js 26.13.0 ran both generator CLIs. Bun 1.3.9 ran the cache and mutation assertions. We type-checked the output and exercised the generated options with a real QueryClient and an in-process Fetch stub. This checks serialization, cache matching and mutation callbacks. For a rollout, run the same assertions against your own auth setup, error responses and hydration path.

Save the spec below as openapi.yaml. The .example host is a placeholder for intercepted requests.

openapi: 3.0.3
info:
  title: Inventory fixture
  version: '1.0.0'
servers:
  - url: https://inventory.example
paths:
  /widgets:
    get:
      operationId: listWidgets
      tags: [widgets]
      parameters:
        - name: state
          in: query
          schema:
            type: string
            enum: [active, archived]
      responses:
        '200':
          description: Matching widgets
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Widget'
    post:
      operationId: createWidget
      tags: [widgets]
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/NewWidget'
      responses:
        '201':
          description: Created widget
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Widget'
        '409':
          description: A widget with that name already exists
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Conflict'
components:
  schemas:
    Widget:
      type: object
      required: [id, name]
      properties:
        id:
          type: string
        name:
          type: string
    NewWidget:
      type: object
      required: [name]
      properties:
        name:
          type: string
    Conflict:
      type: object
      required: [message]
      properties:
        message:
          type: string

Use orval.config.ts for the Orval run.

import { defineConfig } from 'orval';

export default defineConfig({
  inventory: {
    input: './openapi.yaml',
    output: {
      target: './generated/orval/inventory.ts',
      client: 'react-query',
      httpClient: 'fetch',
      baseUrl: { getBaseUrlFromSpecification: true },
    },
  },
});

Use openapi-ts.config.ts for the Hey API run.

import { defineConfig } from '@hey-api/openapi-ts';

export default defineConfig({
  input: './openapi.yaml',
  output: './generated/hey',
  plugins: ['@hey-api/client-fetch', '@tanstack/react-query'],
});

With the pinned generators installed as dev dependencies and React and TanStack Query installed as runtime dependencies, run these from the fixture directory.

bun run orval --config orval.config.ts
bun run openapi-ts -f openapi-ts.config.ts

Each command writes to its own output directory. The Hey API query and mutation factories are in generated/hey/@tanstack/react-query.gen.ts. The Orval hooks and factories are in generated/orval/inventory.ts. For a quick integration check in your app, prefetch the active and archived filters, simulate a duplicate create, then invalidate just the active key. Check that getQueryState(archivedKey)?.isInvalidated is still false before trying the broader filter.

Source notes