# Getting Started (/docs/react/getting-started)

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 [#choose-how-your-hooks-get-their-types]

| Your backend | Types | Routes |
| --- | --- | --- |
| TypeScript `serve` in the same repo | `InferApiType<typeof api>` with `import type` | `hypequery generate:manifest` |
| TypeScript `serve` in another repo | `hypequery generate:client` from a contract exported with `hypequery export:client-contract` | Generated with the types |
| Python (`hypequery.serve`) | `hypequery generate:client` from an exported client contract | Generated with the types |
| hypequery cloud | `hypequery generate:client --cloud` | Generated with the types |

Each path is covered below: [TypeScript](#setup), [TypeScript in another repo](#datasets-served-from-typescript-in-another-repo), [Python](#datasets-served-from-python) and [cloud](/docs/cloud/react).

<Callout type="info" title="What about OpenAPI?">
  Serve's [OpenAPI document](/docs/http-openapi) 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.
</Callout>

## Installation [#installation]

<CodeBlock>
<Pre>
```bash
npm install @hypequery/react @tanstack/react-query
npm install -D @hypequery/cli
```
</Pre>
</CodeBlock>

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 [#setup]

### Automatic type inference (recommended) [#automatic-type-inference-recommended]

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

<CodeBlock>
<Pre>
```bash
npx hypequery generate:manifest analytics/api.ts --output analytics/hypequery-manifest.json
```
</Pre>
</CodeBlock>

<CodeBlock>
<Pre>
```ts
// 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,
});
```
</Pre>
</CodeBlock>

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.

<Callout type="warn" title="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:

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

  `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.
</Callout>

<Callout type="info">
  `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 <a href="/docs/react/advanced-patterns#auto-config-from-server">Auto-config from server</a>. Without a manifest (or an explicit <code>config</code> entry), `useDataset` throws a clear error rather than calling the wrong URL.
</Callout>

### Manual type definition [#manual-type-definition]

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

<CodeBlock>
<Pre>
```ts
// 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,
});
```
</Pre>
</CodeBlock>

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 [#provider-setup]

Wrap your app with TanStack Query's provider:

<CodeBlock>
<Pre>
```tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

export function AppProviders({ children }: { children: React.ReactNode }) {
  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  );
}
```
</Pre>
</CodeBlock>

<CodeBlock>
<Pre>
```tsx
// app.tsx or _app.tsx
import { AppProviders } from './providers';

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

## Datasets served from TypeScript in another repo [#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:

<CodeBlock>
<Pre>
```bash
npx hypequery export:client-contract analytics/api.ts --output client-contract.json
```
</Pre>
</CodeBlock>

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 [#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](/docs/python/client-endpoints#3-export-the-contract) 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:

<CodeBlock>
<Pre>
```bash
npm install -D @hypequery/cli
npx hypequery generate:client client-contract.json --output src/hypequery-client.ts
```
</Pre>
</CodeBlock>

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:

<CodeBlock>
<Pre>
```ts
// 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(),
  });
```
</Pre>
</CodeBlock>

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

### One client per signed-in user [#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:

<CodeBlock>
<Pre>
```tsx
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>
```
</Pre>
</CodeBlock>

`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 [#when-the-servers-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 [#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`.
