clickhouse-js-node-coding

작성자: clickhouse

참조: https://clickhouse.com/docs/integrations/javascript

npx skills add https://github.com/clickhouse/clickhouse-js --skill clickhouse-js-node-coding

ClickHouse Node.js Client — Coding

Reference: https://clickhouse.com/docs/integrations/javascript

⚠️ Node.js runtime only. This skill covers the @clickhouse/client package running in a Node.js runtime exclusively — including Next.js Node runtime API routes, React Server Components, Server Actions, and standard Node.js processes. Do not apply this skill to browser client components, Web Workers, Next.js Edge runtime, Cloudflare Workers, or any usage of @clickhouse/client-web. For browser/edge environments, the correct package is @clickhouse/client-web.


How to Use This Skill

  1. Match the user's intent to a row in the Task Index below and read the corresponding reference file before writing code. After reading it, scan any Answer checklist in that reference and make sure the final answer covers each relevant item; those checklists capture details users usually need but are easy to omit in short answers.
  2. Always import from @clickhouse/client (never @clickhouse/client-web) and create a client with createClient({ url }) or rely on supported defaults when appropriate. Close it with await client.close() preferably when it's no longer needed or during graceful shutdown for global resources.
  3. Prefer JSONEachRow for typical row inserts/selects unless the user has already chosen another format or is streaming raw bytes (CSV / TSV / Parquet — see examples/node/performance/). Note on clickhouse_settings: settings passed to createClient are defaults for every request; they can be overridden per-call by passing clickhouse_settings directly to insert(), query(), or command(). Always mention this when the user configures settings at the client level.
  4. Always use query_params for user-supplied values — never template- literal-interpolate them into SQL. See reference/query-parameters.md. When answering a parameter-binding question, your response must explicitly name template-literal interpolation as a "SQL injection risk" — even when the user only asked about syntax and did not raise security. The literal phrase "SQL injection" needs to appear; this is the most common mistake from PostgreSQL/MySQL users and the security framing is part of the correct answer, not an optional aside.
  5. Pick the right method for the job:
    • client.insert() — write rows.
    • client.query() + resultSet.json() / .text() / .stream() — read rows that return data.
    • client.command() — DDL and other statements that don't return rows (CREATE, DROP, TRUNCATE, ALTER, SET in a session, etc.).
    • client.exec() — when you need the raw response stream of an arbitrary statement (rare in coding scenarios).
    • client.ping() — health check; returns { success, error? }, never throws on connection failure.
  6. Note version constraints when relevant. Examples:
    • pathname config option: client >= 1.0.0.
    • BigInt values in query_params: client >= 1.15.0.
    • TupleParam and JS Map in query_params: client >= 1.9.0.
    • Configurable json.parse / json.stringify: client >= 1.14.0.
    • Time / Time64 data types: ClickHouse server >= 25.6.
    • QBit data type: ClickHouse server >= 25.10 (GA on 26.x).
    • Dynamic / Variant / new JSON types: ClickHouse server >= 24.1 / 24.5 / 24.8 (no longer experimental since 25.3).

Task Index

Identify the user's task and read the matching reference file.

TaskTriggers / symptomsReference file
Configure / connect the clientBuilding a createClient call, URL parameters, clickhouse_settings, default format, custom HTTP headersreference/client-configuration.md
Compress requests / responsescompression, gzip vs zstd, { codec } option shape, Node version requirements, web limitationsreference/compression.md
Ping the serverHealth checks, readiness probes, "is ClickHouse up?"reference/ping.md
Choose an insert format"Which format should I use to insert?", JSON vs raw, JSONEachRow vs JSON vs JSONObjectEachRowreference/insert-formats.md
Insert into a subset of columns / different databaseinsert({ columns }), excluding columns, ephemeral columns, cross-DB insertsreference/insert-columns.md
Insert values, expressions, dates, decimalsINSERT … VALUES with SQL functions, Date/DateTime from JS, Decimal precision, INSERT … SELECT; inserting a UUID into a UInt128 column is tricky — use when the user is writing code that stores a UUID as UInt128reference/insert-values.md
Async inserts (server-side batching)async_insert=1, fire-and-forget vs wait-for-ackreference/async-insert.md
Select and parse resultsJSONEachRow reads, JSON with metadata, picking a select formatreference/select-formats.md
Parameterize queriesBinding values, special characters / escaping, "SQL injection?", {name: Type} syntaxreference/query-parameters.md
Sessions & temporary tablessession_id, CREATE TEMPORARY TABLE, per-session SET commandsreference/sessions.md
Modern data typesDynamic, Variant, JSON (object), Time, Time64, QBit (vector search)reference/data-types.md
Custom JSON parse/stringifyPlug in JSONBig / safe-stable-stringify / a BigInt-aware serializerreference/custom-json.md

Conventions used in answers

  • Always show import { createClient } from '@clickhouse/client' (Node, never Web).
  • Always await client.close() at the end of self-contained snippets; in long-running services, close on graceful shutdown.
  • For inserts, prefer format: 'JSONEachRow' and values: [...] unless the user's scenario requires otherwise.
  • For selects, prefer await (await client.query({...})).json<RowType>() for small / medium result sets; for bigger results suggest streaming.
  • When showing parameter binding, use ClickHouse's native {name: Type} syntax — never $1, ?, or :name.
  • For DDL inside a cluster or behind a load balancer, set clickhouse_settings: { wait_end_of_query: 1 } on the command() call so the server only acknowledges after the change is applied. See https://clickhouse.com/docs/en/interfaces/http/#response-buffering.

Out of scope

This skill covers day-to-day coding against @clickhouse/client (Node). The following topics are intentionally not covered here:

  • Errors, hangs, type mismatches, proxy pathname surprises, log silence, socket hang-ups, ECONNRESET → use the clickhouse-js-node-troubleshooting skill.
  • Streaming, Parquet, file streams, server-side bulk moves, progress streaming, async-insert throughput tuning — see examples/node/performance/.
  • TLS, RBAC / read-only users, deeper SQL-injection guidance — see examples/node/security/.
  • CREATE TABLE patterns, deployment-shaped connection strings, replication / sharding choices — see examples/node/schema-and-deployments/.
  • Browser, Web Worker, Next.js Edge, Cloudflare Workers — use @clickhouse/client-web and see examples/web/.

Still Stuck?

clickhouse의 다른 스킬

chdb-sql
clickhouse
Python에서 직접 ClickHouse SQL을 실행하세요 — 서버가 필요 없습니다. 로컬 파일, 원격 데이터베이스, 클라우드 스토리지를 완전한 ClickHouse SQL 기능으로 쿼리할 수 있습니다.
official
chdb-datastore
clickhouse
DataStore는 지연 실행 방식의 ClickHouse 기반 pandas 대체제입니다. 기존 pandas 코드를 변경 없이 그대로 사용할 수 있지만, 연산은 최적화된 SQL로 컴파일되어 결과가 필요할 때(예: print(), len(), 반복)에만 실행됩니다.
official
clickhouse-architecture-advisor
clickhouse
ClickHouse 아키텍처를 설계하거나, 수집 또는 모델링 패턴 중에서 선택하거나, 모범 사례를 워크로드별 시스템으로 변환할 때 반드시 사용해야 합니다…
official
clickhouse-best-practices
clickhouse
28개의 ClickHouse 모범 사례 규칙으로, 스키마 설계, 쿼리 최적화, 데이터 수집 전략별로 구성되어 있습니다. 기본 키 및 데이터 유형 선택(변경 불가능한 설계 결정), JOIN 및 쿼리 최적화, 삽입 배치 및 변형 회피 등 세 가지 핵심 영역을 다룹니다. 영향도에 따라 우선순위가 매겨진 28개의 규칙을 포함하며, ClickHouse의 컬럼 기반 스토리지 및 희소 인덱스 메커니즘으로 인해 스키마 설계 및 쿼리 최적화 규칙은 CRITICAL로 표시됩니다. 구조화된 검토 절차를 제공합니다...
official
clickhousectl-cloud-deploy
clickhouse
사용자가 ClickHouse를 클라우드에 배포하거나, 프로덕션 환경으로 전환하거나, ClickHouse Cloud를 사용하거나, 관리형 ClickHouse 서비스를 호스팅하거나, 로컬에서 마이그레이션하려는 경우 사용합니다.
official
clickhousectl-local-dev
clickhouse
사용자가 ClickHouse로 애플리케이션을 구축하거나, 로컬 ClickHouse 개발 환경을 설정하거나, ClickHouse를 설치하거나, 로컬 서버를 생성하려는 경우에 사용합니다.
official
setup
clickhouse
이 플러그인에 포함된 ClickHouse MCP 서버 연결 설정을 사용자에게 안내합니다. 사용자가 플러그인을 처음 설치하거나 문제가 있을 때 사용합니다.
official
clickhouse-js-node-troubleshooting
clickhouse
참조: https://clickhouse.com/docs/integrations/javascript
official