Skip to Content
TypeScript SDKServe

Getting Started

Install @hypequery/react and set up typed TanStack Query hooks for a hypequery API, including the provider and datasets served from another repo or from Python.

Use @hypequery/react for type-safe hooks (useQuery, useMutation, useDataset, useMetric) backed by TanStack Query. The hooks need two things from your backend: the types of each endpoint's input and output, and the routes (method and path) they are served on.

Choose how your hooks get their types

Your backendTypesRoutes
TypeScript serve in the same repoInferApiType<typeof api> with import typehypequery generate:manifest
TypeScript serve in another repohypequery generate:client from a contract exported with hypequery export:client-contractGenerated with the types
Python (hypequery.serve)hypequery generate:client from an exported client contractGenerated with the types
hypequery cloudhypequery generate:client --cloudGenerated with the types

Each path is covered below: TypeScript, TypeScript in another repo, Python and cloud.

What about OpenAPI?

Serve's OpenAPI document describes request bodies, but not the rows a dataset query returns: those depend on which dimensions and measures you select, which OpenAPI cannot express. Use the OpenAPI spec for other languages and API tooling, and the paths above for typed React hooks.

Installation

npm install @hypequery/react @tanstack/react-query
npm install -D @hypequery/cli

Peer dependencies: react and react-dom ^18 || ^19, and @tanstack/react-query@^5.104.5. @hypequery/cli provides the hypequery command used below; npx hypequery alone will not find it.

Setup

Generate the route manifest as static JSON, then import the type of your API, never its value:

npx hypequery generate:manifest analytics/api.ts --output analytics/hypequery-manifest.json
// lib/analytics.ts
import { createAnalyticsHooks } from '@hypequery/react';
import type { InferApiType } from '@hypequery/serve';
import type { api } from '@/analytics/api';
import manifest from '@/analytics/hypequery-manifest.json';

// `import type` is erased at build time, so the server module, and the
// ClickHouse client it constructs, never reach the browser bundle.
type Api = InferApiType<typeof api>;

export const {
  useQuery,
  useMutation,
  useMetric,
  useDataset,
  useInfiniteDataset,
} = createAnalyticsHooks<Api>({
  baseUrl: '/api/analytics',
  manifest,
});

The manifest maps every query, metric and dataset key to its method and full path. Serve mounts named queries at /api/analytics/queries/<name> and datasets at /api/analytics/datasets/<name>/query by default, so the hooks need it to call the right URL. Re-run generate:manifest whenever you add or re-route an endpoint, and wire it into your build ("prebuild": "hypequery generate:manifest …") so it cannot drift.

createAnalyticsHooks returns everything createHooks does, plus the semantic hooks. If your API only has named queries, createHooks<Api>({ baseUrl, manifest }) is enough.

Do not import the serve API as a value here

This module is imported by client components, so anything it imports as a value is bundled for the browser. Calling manifest: api.manifest() requires a value import of api, which pulls initServe and @hypequery/clickhouse into the client graph. In a Next.js App Router project that fails the build outright:

./node_modules/@hypequery/clickhouse/dist/cli/generate-types.js:2:1
Error: Module not found: Can't resolve 'fs/promises'

api.manifest() is a server-side API. Use it in your build step, in a config endpoint, or anywhere else that only runs on the server, not in the module that exports your hooks.

api.manifest() output is plain JSON, so you can also serve it from a small endpoint and fetch it at runtime when a static file does not suit your setup. See Auto-config from server. Without a manifest (or an explicit config entry), useDataset throws a clear error rather than calling the wrong URL.

Manual type definition

When the frontend cannot see the server's types, write them by hand. Keep the generated manifest for routes:

// lib/analytics.ts
import { createHooks } from '@hypequery/react';
import manifest from './hypequery-manifest.json';

type Api = {
  weeklyRevenue: {
    input: { startDate: string };
    output: { total: number };
  };
  // ... other queries
};

export const { useQuery, useMutation } = createHooks<Api>({
  baseUrl: '/api/analytics',
  manifest,
});

Hand-written types are not checked against the server, so they can drift. Prefer a shared types package that exports type Api = InferApiType<typeof api> when the two repos can share one.

Provider Setup

Wrap your app with TanStack Query's provider:

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

export function AppProviders({ children }: { children: React.ReactNode }) {
  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
}
// app.tsx or _app.tsx
import { AppProviders } from './providers';

function App() {
  return (
    <AppProviders>
      <YourApp />
    </AppProviders>
  );
}

Datasets served from TypeScript in another repo

When the frontend can't import the API module, InferApiType has nothing to infer from. Export the API's client contract instead: a JSON description of each dataset and metric endpoint's fields, limits, full path and schema hash.

1. Export the contract in the backend repo and commit it, or publish it as a build artifact:

npx hypequery export:client-contract analytics/api.ts --output client-contract.json

The module must export the value createAPI() returns, as api or as the default export. api.clientContract() returns the same contract in code. Paths include basePath. If the API is mounted below a prefix, for example app.use('/analytics', toNodeHandler(api)), set clientContract: { mountPath: '/analytics' } in createAPI so the contract names the paths browsers call. Run the command with --check in CI to fail when the committed contract is stale.

The contract advertises dataset fields, base and derived measures, and metrics. Window and shift measures, relationship fields and metrics with a fixed grain (metric.by('month')) are not in it yet. Query those through the other paths above.

2. Generate the client and create the hooks in the React app, exactly as for Python below: npx hypequery generate:client client-contract.json --output src/hypequery-client.ts, then pass clientManifest and ClientApi to createAnalyticsHooks.

Requests from the generated client send each endpoint's schema hash. TypeScript serve answers a stale hash with 409 CLIENT_SCHEMA_CHANGED, and holds a matching request to the contract's strict query profile, as Python does. Requests without the header, such as those from InferApiType hooks, are served as before. Browsers calling another origin need X-Hypequery-Client-Schema in the CORS allow-list, which the default cors: true settings include.

Datasets served from Python

A Python backend (hypequery.serve) has no TypeScript API type to infer. Instead, it exports a client contract: a JSON description of each endpoint's fields, limits and schema hash. Generate a typed client file from it, then pass that file's API type and route map to the hooks.

1. Export the contract from the Python project, with python -m hypequery export client-contract --factory analytics.api:api (pointing at your API) or hypequery.serve.export_client_contract(app). Export the build contract, not the live /v1/client-contract route, which returns the caller's authorized view and which generate:client refuses. Python: React and MCP clients covers the backend setup. Only endpoints installed with a client profile appear in the contract: pass client_profile= to create_api(datasets={...}) for its Dataset entries, or to create_dataset_endpoint(...). An export with no endpoints fails and names the routes that lack one.

2. Generate the client in the React app. generate:client lives in the Node CLI, so install it as a dev dependency first; npx hypequery alone will not find it:

npm install -D @hypequery/cli
npx hypequery generate:client client-contract.json --output src/hypequery-client.ts

The file exports ClientApi (request and response types), clientManifest (routes and schema hashes) and clientContractHash. Run it with --check in CI to fail on drift, and with --force to overwrite after reviewing a change.

3. Create the hooks. Pass the endpoint origin as baseUrl; the generated paths already include the server's mount prefix:

// lib/analytics.ts
import { createAnalyticsHooks } from '@hypequery/react';
import { clientManifest, type ClientApi } from '@/hypequery-client';

export const { useDataset, useMetric, useInfiniteDataset, useInfiniteMetric } =
  createAnalyticsHooks<ClientApi>({
    baseUrl: 'https://analytics.example.com',
    manifest: clientManifest,
    token: () => getShortLivedUserToken(),
  });

Every generated route is a POST, whatever the default method on other routes.

One client per signed-in user

When users sign in and out in the same page, create a client per session with createHypequeryClient and provide it, with its own QueryClient, through HypequeryProvider. Hooks created without a config read the client from the provider:

import { QueryClient } from '@tanstack/react-query';
import { HypequeryProvider, createAnalyticsHooks, createHypequeryClient } from '@hypequery/react';
import { clientContractHash, clientManifest, type ClientApi } from '@/hypequery-client';

export const hooks = createAnalyticsHooks<ClientApi>();

function signIn(token: string) {
  return {
    client: createHypequeryClient<ClientApi>({
      baseUrl: 'https://analytics.example.com',
      manifest: clientManifest,
      token,
      cacheKey: `${clientContractHash}:${crypto.randomUUID()}`,
    }),
    queries: new QueryClient(),
  };
}

// <HypequeryProvider client={session.client} queryClient={session.queries}>…</HypequeryProvider>

cacheKey scopes the TanStack cache. Use a new client, or a new cacheKey, whenever the deployment, user or authorization scope changes. Changing what a token resolver returns does not invalidate cached data.

When the server's contract changes

Every request sends its endpoint's schema hash in X-Hypequery-Client-Schema. If the server's definitions have changed since the client was generated, the server answers 409 with details.code CLIENT_SCHEMA_CHANGED instead of returning data in a shape your types don't describe. The hooks do not fetch a new contract. Export it again, regenerate the client, and review the type errors.

Result types

  • Rows contain exactly the selected fields. Omitted measures select the endpoint's default measures; measures: [] selects none.
  • Fields named in a literal selection (dimensions: ['country']) are always present. Fields picked from a runtime string[] are optional, since the compiler can't know which were chosen.
  • Measure values are string | null, so decimals keep their precision.
  • Numeric dimensions are number | string | null, and timestamps are strings.
  • Dimensions include null: the contract doesn't declare columns non-nullable, and related fields are always nullable.
  • Metric rows contain the metric under its name, plus period when you pass by.

On this page

Get early access to hypequery cloud.

Cloud hosts the same model you run in your backend, with a managed API and MCP server, versions, and rollback. We're letting teams in a few at a time. Join the waitlist and we'll reach out when your project can go live.

How do you want to build your analytics layer? (Optional)
What features do you most need? (Optional)

Pick as many as you like.

Only your email is required. All other questions are optional.