ClickHouse TypeScript client

A TypeScript client for ClickHouse and ClickHouse Cloud

The official TypeScript client for ClickHouse Cloud is @clickhouse/client for Node.js, or @clickhouse/client-web for browsers and Cloudflare Workers, connecting over HTTPS on port 8443. hypequery builds on it and connects to ClickHouse Cloud, self-hosted ClickHouse, or a local container with the same code. The annoying part of using ClickHouse from TypeScript is not writing SQL. It is keeping runtime types, query code, and API surfaces aligned as the codebase grows. hypequery gives you generated schema types and a reusable query layer so that work does not keep getting rebuilt by hand.

Core benefit

Generated schema types

Execution model

Local or HTTP

Best fit

Analytics-heavy TypeScript apps

ClickHouse types do not map cleanly to JavaScript

DateTime values come back as strings, UInt64 values often need to stay strings, and Nullable columns return null. If you hand-write TypeScript interfaces, TypeScript trusts the wrong types.

Raw SQL strings do not scale across a product codebase

The same analytics query ends up duplicated in API routes, background jobs, dashboards, and internal tools. Refactors become fragile because the query contract is spread across string literals.

Most teams end up rebuilding the same analytics layer

Once a ClickHouse project grows, teams want generated schema types, reusable query definitions, typed APIs, and a clean way to share analytics logic between backend and frontend.

How hypequery helps

A ClickHouse TypeScript workflow built for reusable analytics

Instead of hand-writing TypeScript interfaces and copying SQL into route handlers, jobs, and dashboards, you generate schema types from ClickHouse and define the query once. That definition can run locally or be served over HTTP without drifting from the source query.

  • Generate TypeScript schema types from your live ClickHouse database
  • Build type-safe ClickHouse queries without hand-maintained interfaces
  • Reuse the same analytics definitions across APIs, jobs, and dashboards
  • Expose typed HTTP endpoints with request and response schemas
  • Keep ClickHouse runtime types aligned with your TypeScript codebase

Step 1

Generate schema types from ClickHouse

generate-schema.sh
npx hypequery generate --output analytics/schema.ts

This is where the ClickHouse TypeScript workflow becomes reliable. Runtime types like `DateTime`, `UInt64`, `Nullable`, and `Decimal` get mapped correctly instead of being guessed.

Step 2

Define typed ClickHouse queries once

hypequery lets you model analytics queries in TypeScript and reuse them across product surfaces. That means the same query definition can power a dashboard, an API route, a job, or an internal tool without duplicating logic.

This is the difference between “ClickHouse client in TypeScript” and a real ClickHouse analytics backend in TypeScript. You are not just running queries. You are defining typed contracts that can be reused safely.

If you want the shortest path to a working setup, skip the comparison content and start with hypequery now. One real query against your own schema will tell you more than another hour of reading.

If your team is comparing options, read hypequery vs @clickhouse/client, hypequery vs Kysely, and hypequery vs Drizzle after this page.

analytics-api.ts
const { query, serve } = initServe({
  context: () => ({ db }),
});

const revenueByDay = query({
  input: z.object({
    startDate: z.string(),
    endDate: z.string(),
  }),
  query: async ({ ctx, input }) => {
    return ctx.db
      .table('orders')
      .where('created_at', 'gte', input.startDate)
      .where('created_at', 'lte', input.endDate)
      .groupBy(['day'])
      .sum('total', 'revenue')
      .execute();
  },
});

const api = serve({
  queries: { revenueByDay },
});

api.route('/revenue-by-day', api.queries.revenueByDay, { method: 'POST' });

ClickHouse Cloud

Use ClickHouse Cloud from TypeScript

The official @clickhouse/client connects to ClickHouse Cloud and leaves the result types to you. hypequery uses that same client as its transport and adds the parts a ClickHouse Cloud TypeScript app needs next: types generated from the tables in your Cloud service, a typed query builder, and query definitions you can serve as HTTP endpoints. Copy the HTTPS URL and password from the Connect dialog of your service, then:

1. Point the CLI at your Cloud service

.env + terminal
# From the Connect dialog of your ClickHouse Cloud service
CLICKHOUSE_URL=https://abc123xyz.eu-west-1.aws.clickhouse.cloud:8443
CLICKHOUSE_USERNAME=default
CLICKHOUSE_PASSWORD=your-service-password
CLICKHOUSE_DATABASE=default

# Install the client and CLI in your project
npm install @hypequery/clickhouse
npm install -D @hypequery/cli

# Generates types from the tables in your Cloud service
npx hypequery generate --output analytics/schema.ts

2. Query it with generated types

analytics/db.ts
import { createQueryBuilder } from '@hypequery/clickhouse';
import type { IntrospectedSchema } from './schema.js';

export const db = createQueryBuilder<IntrospectedSchema>({
  url: process.env.CLICKHOUSE_URL!, // https://<service>.<region>.<cloud>.clickhouse.cloud:8443
  username: process.env.CLICKHOUSE_USERNAME!,
  password: process.env.CLICKHOUSE_PASSWORD!,
  database: process.env.CLICKHOUSE_DATABASE!,
});

// Rows are typed from your Cloud schema, not hand-written interfaces
const topPages = await db
  .table('page_views')
  .select(['path'])
  .count('path', 'views')
  .groupBy(['path'])
  .orderBy('views', 'DESC')
  .limit(10)
  .execute();

HTTPS on port 8443

ClickHouse Cloud serves the HTTP interface over TLS on port 8443. hypequery runs on @clickhouse/client underneath, so the same connection URL from the Cloud console works unchanged.

Types from the service you deploy against

Point the CLI at a development or staging Cloud service and commit the generated schema file. Regenerate in CI when tables change, and the build fails where query code no longer matches.

Idle services and cold starts

Cloud services can idle when no queries arrive. The first query after a pause can take longer while the service wakes, so set request timeouts with that in mind.

Same code for self-hosted and local

Only the URL changes between ClickHouse Cloud, a self-hosted cluster, and a local Docker container. The query code, generated types, and API definitions stay the same.

Deciding between ClickHouse Cloud and a hosted API platform? Read ClickHouse Cloud vs Tinybird. Weighing the raw client? Read hypequery vs @clickhouse/client.

Why teams search for this

Common ClickHouse TypeScript problems this page should solve

ClickHouse query builder for TypeScript

If you want a ClickHouse query builder with real TypeScript support, the key question is not just syntax. It is whether the builder understands ClickHouse runtime types and can be reused across your app.

ClickHouse types in TypeScript

DateTime, UInt64, Decimal, and Nullable columns are where most silent bugs start. If that is your main pain point, read the type problem guide.

Reusable analytics APIs in TypeScript

Teams often start with raw queries and then realize they need typed APIs, internal analytics services, or OpenAPI docs on top. hypequery is optimized for that step-up in complexity.

Alternatives to hand-written query types

Hand-maintained interfaces drift. Generated schema types plus typed query definitions remove that drift from the system instead of relying on discipline alone.

How do I use ClickHouse with TypeScript?

Start by introspecting the live schema. Generate TypeScript types from that schema. Build queries against those types. Then decide where the query needs to run: inline, behind an endpoint, or in a dashboard. That is the workflow hypequery makes easier.

Does hypequery work with ClickHouse Cloud?

Yes. Use the HTTPS URL on port 8443 from your service's Connect dialog as the host, with the service username and password. Schema generation, the query builder, and served endpoints all work the same as on self-hosted ClickHouse. See the ClickHouse Cloud setup above.

Further reading

Compare approaches and go deeper

Examples

Runnable examples

Every example runs against the same seeded ClickHouse dataset. Scaffold one with npx @hypequery/cli create <slug> -y, or browse the full list.

Guide · ClickHouse 25.8

ClickHouse with Docker Compose: a pinned, persistent local server with a million-row sample dataset

Run ClickHouse 25.8 in Docker Compose with a healthcheck, a password, volumes and a 1M-row sample dataset, then connect from Node, Python and hypequery.

Quantile

Open guide

Recipe · TypeScript

Cursor pagination in ClickHouse: keyset vs LIMIT/OFFSET, measured

Page a tenant's events newest first with a keyset cursor on (occurred_at, event_id) and see from EXPLAIN and query_log why it beats OFFSET on deep pages.

Node.jsClickHouseAPIPagination

Open recipe

Recipe · TypeScript

Tenant lookups with a ClickHouse dictionary and dictGet in a typed dataset

Load tenant plan and region into a ClickHouse dictionary, expose them as dataset dimensions via dictGet, and check the result and timing against a JOIN.

Node.jsClickHouseSaaS analyticsMulti-tenant

Open recipe

Recipe · TypeScript

Funnel analysis in ClickHouse with windowFunnel and a typed dataset

Count users through login, query and export within 24 hours per tenant with windowFunnel, get conversion per step, and see what each strict mode changes.

Node.jsClickHouseProduct analyticsFunnels

Open recipe

Recipe · TypeScript

Ordered per-user event timelines in ClickHouse with groupArray, arraySort and groupArraySorted

Build each user's event timeline in time order. groupArray's order is not guaranteed; sorting (time, id, value) tuples or groupArraySorted fixes it.

Node.jsClickHouseProduct analyticsUser journeys

Open recipe

Recipe · TypeScript

ISO weeks in ClickHouse: toMonday buckets and %G-W%V labels across the year boundary

Bucket events into Monday-to-Sunday ISO weeks with labels like 2026-W01, and see where toStartOfWeek, %Y and toWeek go wrong at new year.

Node.jsClickHouseTime seriesProduct analytics

Open recipe

Example · TypeScript

ClickHouse materialized view rollups: incremental vs refreshable

Pre-aggregate a million events two ways, incremental and refreshable, and query both through one typed hypequery dataset.

Node.jsClickHousePre-aggregationDashboardsTime series

Open example

Recipe · TypeScript

Latency and status buckets in ClickHouse with multiIf, as reusable dataset dimensions

Define latency and status-class buckets once with multiIf, keep them in bucket order, and see how CASE, transform and roundDown compare on real requests.

Node.jsClickHouseObservabilityProduct analytics

Open recipe

Example · TypeScript

Next.js dashboard on ClickHouse with cross-filtering

A Next.js 16 dashboard over ClickHouse: one typed dataset, a serve endpoint, React hooks, and click-to-filter across every panel.

Next.jsReactClickHouseDashboardsProduct analyticsEmbedded analytics

Open example

Recipe · TypeScript

p95 latency per event type in ClickHouse with a typed dataset

Define p50, p95 and p99 latency once as dataset measures and get the quantile() SQL, the result on a million events, and the exactness trade-off.

Node.jsClickHouseObservabilityTime series

Open recipe

Example · TypeScript

Add ClickHouse analytics to a Postgres + Drizzle app

Keep accounts in Postgres with Drizzle, serve usage from ClickHouse with hypequery, and join the two by account id in one API route.

Node.jsHonoDrizzlePostgresClickHouseSaaS analyticsUsage analyticsPostgres to ClickHouse

Open example

Recipe · TypeScript

Add a ClickHouse projection that a typed dataset query uses automatically

Add a sort-key and an aggregate projection to a ClickHouse table, then prove with EXPLAIN and query_log that an unchanged dataset query reads from them.

Node.jsClickHousePerformanceTime series

Open recipe

Recipe · TypeScript

Upserts and deletes in ClickHouse with ReplacingMergeTree and a typed dataset

Upsert and delete rows with ReplacingMergeTree, read the latest version with FINAL or argMax, and pin the results before and after OPTIMIZE.

Node.jsClickHouseSaaS analyticsData modeling

Open recipe

Recipe · TypeScript

Weekly retention cohorts in ClickHouse with a typed dataset

Turn signup cohorts and weekly activity into a retention dataset: cohort size, active users and retention ratio, sliceable by cohort and week offset.

Node.jsClickHouseProduct analyticsRetention

Open recipe

Recipe · TypeScript

Sessionization in ClickHouse with lagInFrame and a typed dataset

Split events into 30-minute inactivity sessions per user with lagInFrame and a running sum, then count sessions and average their length with a dataset.

Node.jsClickHouseProduct analyticsSessions

Open recipe

Recipe · TypeScript

Top N per group in ClickHouse with LIMIT BY, compared with row_number() and rank()

Get the top 3 paths for every tenant in one query with LIMIT 3 BY, typed in TypeScript, and see how ties change the answer under rank() and dense_rank().

Node.jsClickHouseProduct analyticsMulti-tenant

Open recipe

Example · TypeScript

Usage-based billing on ClickHouse: metering, invoice previews and MRR

Meter per-tenant usage in ClickHouse and turn it into Decimal-exact invoice previews, a usage-this-month API and MRR, from one TypeScript definition.

Node.jsHonoClickHouseBillingUsage meteringSaaS analyticsMulti-tenant

Open example

Next step

Start with hypequery on one real ClickHouse query

Generate schema types, define your first typed query, and prove the workflow on your actual ClickHouse schema before expanding further.

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.