Skip to main content
Build your agent on Neon and provision backends you fully control. See how Ideavo does it
/Realtime/TypeScript

TypeScript SDK

Seal queries, subscribe from clients, and sync with frameworks

View as Markdown

Upgrading to 0.2.0

Realtime SDK 0.2.0 uses version 2 of the Realtime protocol. Upgrade @neon/realtime and every Realtime adapter you use (@neon/realtime-react, @neon/realtime-tanstack, @neon/realtime-drizzle, @neon/realtime-kysely) to 0.2.0 together, since the 0.2.0 adapters require @neon/realtime 0.2.0.

The Realtime SDK is split into modules:

Beta: APIs may change

The TypeScript SDK is still evolving. The APIs are subject to change.

Backend

Import the Backend module from @neon/realtime/server. It runs only on your server, because it uses your Realtime secret. It defines live queries and seals them, so an untrusted client can subscribe to a query without being able to read or change it. It's taught in the Defining queries guide.

Create the server once, then seal a query:

import { createRealtime } from "@neon/realtime/server"

const realtime = createRealtime({ secret: process.env.NEON_REALTIME_SECRET!, db: "neondb" })
const sealedQuery = await realtime.seal({ query: messagesQuery(userId, channelId) })

secret is your NEON_REALTIME_SECRET, written by neon env pull --service realtime or shown on the Realtime page in the Neon Console. db is the database your queries run against. Setup covers both, and RealtimeServerOptions lists the other options, including debugMode.

Direct subscriptions

Add a url to createRealtime() and it returns a RealtimeDirectServer, which subscribes to queries itself, for workers, trusted agents and other backend code. Subscribe in trusted backend code shows how.

Typed parameters

Most rawSql parameter values pass as they are. Wrap dates, JSON, bytea and arrays in a pgParam helper to name their Postgres type, as Parameter types shows.

Import specifier @neon/realtime/server

Symbols

SymbolKindSummary
createRealtimeFunctionCreate a server-only Realtime SDK. seal() performs local encryption and no network requests. Supplying a WebSocket url additionally enables trusted direct subscriptions that mint and refresh their own capabilities. Keep the project secret out of browser bundles.
encodeTextParameterFunctionEncode an already unambiguous scalar as a PostgreSQL text-format parameter. This low-level helper is intended for adapter authors. Application code using raw SQL should prefer pgParam for ambiguous PostgreSQL types.
isTypedRawSqlParameterFunctionTest whether a value was created by one of the pgParam helpers. This low-level helper is intended for query-adapter authors. Applications should normally pass the wrapper directly to the adapter or rawSql.
rawSqlFunctionDefine a typed raw SQL query. Values are sent separately from the SQL. Bare values use type OID 0, asking PostgreSQL to infer their types from the SQL. Use pgParam when a value needs an explicit PostgreSQL encoder and built-in type OID. JavaScript null represents SQL NULL.
PostgresParameterHelpersInterfacePostgreSQL text encoders for values that bare raw SQL cannot disambiguate.
PreparedLiveQueryInterfaceAdapter-independent query encrypted into a live-query capability.
PreparedLiveQueryParameterInterfaceOne PostgreSQL text-format Bind parameter in a prepared live query.
RawSqlQueryInterfaceParameterized raw PostgreSQL SQL carrying its declared result-row type.
RealtimeAdapterInterfaceConverts an ORM-native query into the prepared live-query representation.
RealtimeDirectServerInterfaceServer-only SDK with trusted direct-query subscriptions. Each subscription prepares and encrypts its query locally, then uses a shared low-level client and refreshes its capability automatically. It retains its rows while connecting through retryable outages and transparently replaces an expired subscription after connectivity returns.
RealtimeDirectServerOptionsInterfaceConfiguration that enables trusted direct-query subscriptions.
RealtimeServerInterfaceServer-only Realtime capability issuer.
RealtimeServerOptionsInterfaceConfiguration for a server-only Realtime capability issuer.
SealedLiveQueryInterfaceJSON-compatible sealed representation of one exact live query. The query is a short-lived bearer credential. Transport it over HTTPS and do not put it in URLs, logs, or persistent browser storage.
TypedRawSqlParameterInterfaceA raw SQL parameter with an explicit PostgreSQL text encoder and type hint.
RawSqlParameterType aliasA JavaScript value accepted as a PostgreSQL text-format parameter.
RealtimeAdapterSourceType aliasBounded query-builder family recorded in encrypted capabilities.
pgParamVariableHelpers for values whose PostgreSQL text encoding or type is ambiguous.

createRealtime

function createRealtime<Query = RawSqlQuery<unknown>>(options: RealtimeDirectServerOptions<Query>): RealtimeDirectServer<Query>

Create a server-only Realtime SDK.

seal() performs local encryption and no network requests. Supplying a WebSocket url additionally enables trusted direct subscriptions that mint and refresh their own capabilities. Keep the project secret out of browser bundles.

Returns: A reusable capability issuer, extended with direct subscriptions when url is present.

Throws: If the secret or database name is invalid.

Type parameters

NameDefaultDescription
QueryRawSqlQuery<unknown>Query object accepted by the configured adapter.

Parameters

NameTypeDescription
optionsRealtimeDirectServerOptions<Query>Server-only secret, database name, and optional query adapter.

Returns

RealtimeDirectServer<Query>

function createRealtime<Query = RawSqlQuery<unknown>>(options: RealtimeServerOptions<Query>): RealtimeServer<Query>

Create a server-only Realtime SDK.

seal() performs local encryption and no network requests. Supplying a WebSocket url additionally enables trusted direct subscriptions that mint and refresh their own capabilities. Keep the project secret out of browser bundles.

Returns: A reusable capability issuer, extended with direct subscriptions when url is present.

Throws: If the secret or database name is invalid.

Type parameters

NameDefaultDescription
QueryRawSqlQuery<unknown>Query object accepted by the configured adapter.

Parameters

NameTypeDescription
optionsRealtimeServerOptions<Query>Server-only secret, database name, and optional query adapter.

Returns

RealtimeServer<Query>

encodeTextParameter

function encodeTextParameter(value: string | number | bigint | boolean | null, typeOid: number = 0): PreparedLiveQueryParameter

Encode an already unambiguous scalar as a PostgreSQL text-format parameter.

This low-level helper is intended for adapter authors. Application code using raw SQL should prefer pgParam for ambiguous PostgreSQL types.

Returns: An immutable prepared parameter.

Parameters

NameTypeDescription
valuestring | number | bigint | boolean | nullScalar value, or null for SQL NULL.
typeOidnumberPostgreSQL type OID hint, or 0 for SQL-context inference.

Returns

PreparedLiveQueryParameter

isTypedRawSqlParameter

function isTypedRawSqlParameter(value: unknown): value is TypedRawSqlParameter

Test whether a value was created by one of the pgParam helpers.

This low-level helper is intended for query-adapter authors. Applications should normally pass the wrapper directly to the adapter or rawSql.

Parameters

NameTypeDescription
valueunknown

Returns

value is TypedRawSqlParameter

rawSql

function rawSql<Row>(sql: string, parameters: readonly RawSqlParameter[] = []): RawSqlQuery<Row>

Define a typed raw SQL query. Values are sent separately from the SQL. Bare values use type OID 0, asking PostgreSQL to infer their types from the SQL. Use pgParam when a value needs an explicit PostgreSQL encoder and built-in type OID. JavaScript null represents SQL NULL.

Returns: An immutable query descriptor accepted by seal().

Type parameters

NameDefaultDescription
RowRow returned by the query.

Parameters

NameTypeDescription
sqlstringParameterized SQL using PostgreSQL placeholders such as $1.
parametersreadonly RawSqlParameter[]Values in placeholder order.

Returns

RawSqlQuery<Row>

PostgresParameterHelpers

interface PostgresParameterHelpers

PostgreSQL text encoders for values that bare raw SQL cannot disambiguate.

Members

NameTypeDescription
array(elementType: string, values: readonly unknown[]) => TypedRawSqlParameterEncode a possibly nested PostgreSQL array. Built-in element types supply their stable array OID; database-specific or unknown element types use OID 0. JavaScript null becomes a SQL NULL array element. Values are encoded immediately, so later mutations do not affect the parameter.
bytea(value: Uint8Array) => TypedRawSqlParameterEncode bytes in PostgreSQL's hexadecimal bytea text format.
date(value: string | Date) => TypedRawSqlParameterEncode a JavaScript date as a PostgreSQL date. A Date uses its UTC calendar date. A string is passed through as an already encoded PostgreSQL text value.
json(value: unknown) => TypedRawSqlParameterEncode a JavaScript value as PostgreSQL json.
jsonb(value: unknown) => TypedRawSqlParameterEncode a JavaScript value as PostgreSQL jsonb.
text(sqlType: string, value: string | number | bigint | boolean | null) => TypedRawSqlParameterUse an already encoded PostgreSQL text value for a named type. A recognized built-in type supplies its stable OID. Unknown, database-specific, and extension types use OID 0 for inference.
timestamp(value: string | Date) => TypedRawSqlParameterEncode a JavaScript date as a UTC PostgreSQL timestamp without time zone. A string is passed through as an already encoded PostgreSQL text value.
timestamptz(value: string | Date) => TypedRawSqlParameterEncode a JavaScript date as a PostgreSQL timestamptz. A Date uses its ISO 8601 representation. A string is passed through as an already encoded PostgreSQL text value.

PreparedLiveQuery

interface PreparedLiveQuery

Adapter-independent query encrypted into a live-query capability.

Members

NameTypeDescription
parametersreadonly PreparedLiveQueryParameter[]PostgreSQL text-format Bind values and type hints in placeholder order.
sqlreadonly stringParameterized SQL. Adapters must never interpolate runtime values here.

PreparedLiveQueryParameter

interface PreparedLiveQueryParameter

One PostgreSQL text-format Bind parameter in a prepared live query.

Members

NameTypeDescription
typeOidreadonly numberPostgreSQL type OID hint, or 0 to request SQL-context inference.
valuereadonly string | nullPostgreSQL text-format value, or null for SQL NULL.

RawSqlQuery

interface RawSqlQuery<Row> extends PreparedLiveQuery

Parameterized raw PostgreSQL SQL carrying its declared result-row type.

Members

NameTypeDescription
parametersreadonly PreparedLiveQueryParameter[]PostgreSQL text-format Bind values and type hints in placeholder order.
sqlreadonly stringParameterized SQL. Adapters must never interpolate runtime values here.

RealtimeAdapter

interface RealtimeAdapter<Query>

Converts an ORM-native query into the prepared live-query representation.

Members

NameTypeDescription
querySource?readonly RealtimeAdapterSourceQuery-builder family used for aggregate Realtime usage metrics. Official adapters set this automatically; custom adapters may omit it.
prepare(query: Query) => PreparedLiveQueryConvert an adapter-native query into parameterized SQL and text-format parameter values. Adapters may supply PostgreSQL type OID hints; 0 requests inference. The proxy supplies result types.

RealtimeDirectServer

interface RealtimeDirectServer<Query> extends RealtimeServer<Query>

Server-only SDK with trusted direct-query subscriptions.

Each subscription prepares and encrypts its query locally, then uses a shared low-level client and refreshes its capability automatically. It retains its rows while connecting through retryable outages and transparently replaces an expired subscription after connectivity returns.

Members

NameTypeDescription
close() => voidPermanently close every direct subscription and the shared WebSocket.
seal<ConcreteQuery>(input: SealInput<ConcreteQuery>) => Promise<SealedLiveQuery<QueryRow<ConcreteQuery>>>Encrypt a concrete query as a short-lived sealed query. Raw queries produced by rawSql are always accepted. Other query objects are prepared by the configured adapter. SQL validation is deferred to the Realtime proxy when the capability is used.
subscribe<ConcreteQuery>(query: ConcreteQuery, options?: MaterializedLiveQueryOptions<QueryRow<ConcreteQuery>>) => Promise<MaterializedLiveQuerySubscription<QueryRow<ConcreteQuery>>> & <ConcreteQuery>(query: ConcreteQuery, options: RawLiveQueryOptions) => Promise<RawLiveQuerySubscription<QueryRow<ConcreteQuery>>>Subscribe to a query and retain its current materialized rows.

RealtimeDirectServer.seal

seal<ConcreteQuery>(input: SealInput<ConcreteQuery>): Promise<SealedLiveQuery<QueryRow<ConcreteQuery>>>

Encrypt a concrete query as a short-lived sealed query.

Raw queries produced by rawSql are always accepted. Other query objects are prepared by the configured adapter. SQL validation is deferred to the Realtime proxy when the capability is used.

Returns: A JSON-compatible bearer capability with its public fingerprint and expiry.

Throws: If no adapter can prepare the query or capability encryption fails.

Parameters

NameTypeDescription
inputSealInput<ConcreteQuery>Concrete query to seal.

RealtimeDirectServer.subscribe

subscribe<ConcreteQuery>(query: ConcreteQuery, options?: MaterializedLiveQueryOptions<QueryRow<ConcreteQuery>>): Promise<MaterializedLiveQuerySubscription<QueryRow<ConcreteQuery>>>

Subscribe to a query and retain its current materialized rows.

Returns: An independently disposable subscription after its initial capability has been minted locally.

Throws: If the query is invalid or the direct client has been closed.

Parameters

NameTypeDescription
queryConcreteQueryConcrete raw SQL or adapter-native query.
options?MaterializedLiveQueryOptions<QueryRow<ConcreteQuery>>Materialization and optional preloaded-row settings.
subscribe<ConcreteQuery>(query: ConcreteQuery, options: RawLiveQueryOptions): Promise<RawLiveQuerySubscription<QueryRow<ConcreteQuery>>>

Subscribe to complete rows and atomic change batches without retaining rows.

Returns: An independently disposable raw subscription after its initial capability has been minted locally.

Throws: If the query is invalid or the direct client has been closed.

Parameters

NameTypeDescription
queryConcreteQueryConcrete raw SQL or adapter-native query.
optionsRawLiveQueryOptionsSet materialize to false to consume raw events.

RealtimeDirectServerOptions

interface RealtimeDirectServerOptions<Query> extends RealtimeServerOptions<Query>

Configuration that enables trusted direct-query subscriptions.

Members

NameTypeDescription
adapter?readonly RealtimeAdapter<Query>Adapter for ORM-native queries; omit when sealing only raw SQL.
dbreadonly stringPostgreSQL database for this SDK instance. It is embedded in every query capability. The first capability accepted on a WebSocket binds that connection to this database.
debugMode?readonly booleanInclude full database error details in subscription errors. Enable this only in development. Detailed errors can expose schema names, table names, column names, and other database structure to clients.
logger?readonly RealtimeLoggerStructured diagnostic sink for the internal direct-subscription client.
logLevel?readonly RealtimeLogLevelMinimum diagnostic level for the internal direct-subscription client.
parsers?readonly Readonly<Record<number, PostgreSQLBytesParser<unknown> | PostgreSQLTextParser<unknown>> & BuiltInParsers>PostgreSQL result-parser overrides for trusted direct subscriptions.
secretreadonly stringOpaque server-only credential issued by Realtime.
urlreadonly stringRealtime WebSocket endpoint URL. Supplying it adds subscribe() and close() to the returned SDK.

RealtimeDirectServerOptions.debugMode

readonly debugMode?: boolean

Include full database error details in subscription errors.

Enable this only in development. Detailed errors can expose schema names, table names, column names, and other database structure to clients.

Default

false

RealtimeServer

interface RealtimeServer<Query>

Server-only Realtime capability issuer.

Members

NameTypeDescription
seal<ConcreteQuery>(input: SealInput<ConcreteQuery>) => Promise<SealedLiveQuery<QueryRow<ConcreteQuery>>>Encrypt a concrete query as a short-lived sealed query. Raw queries produced by rawSql are always accepted. Other query objects are prepared by the configured adapter. SQL validation is deferred to the Realtime proxy when the capability is used.

RealtimeServer.seal

seal<ConcreteQuery>(input: SealInput<ConcreteQuery>): Promise<SealedLiveQuery<QueryRow<ConcreteQuery>>>

Encrypt a concrete query as a short-lived sealed query.

Raw queries produced by rawSql are always accepted. Other query objects are prepared by the configured adapter. SQL validation is deferred to the Realtime proxy when the capability is used.

Returns: A JSON-compatible bearer capability with its public fingerprint and expiry.

Throws: If no adapter can prepare the query or capability encryption fails.

Parameters

NameTypeDescription
inputSealInput<ConcreteQuery>Concrete query to seal.

RealtimeServerOptions

interface RealtimeServerOptions<Query>

Configuration for a server-only Realtime capability issuer.

Members

NameTypeDescription
adapter?readonly RealtimeAdapter<Query>Adapter for ORM-native queries; omit when sealing only raw SQL.
dbreadonly stringPostgreSQL database for this SDK instance. It is embedded in every query capability. The first capability accepted on a WebSocket binds that connection to this database.
debugMode?readonly booleanInclude full database error details in subscription errors. Enable this only in development. Detailed errors can expose schema names, table names, column names, and other database structure to clients.
secretreadonly stringOpaque server-only credential issued by Realtime.

RealtimeServerOptions.debugMode

readonly debugMode?: boolean

Include full database error details in subscription errors.

Enable this only in development. Detailed errors can expose schema names, table names, column names, and other database structure to clients.

Default

false

SealedLiveQuery

interface SealedLiveQuery<Row>

JSON-compatible sealed representation of one exact live query.

The query is a short-lived bearer credential. Transport it over HTTPS and do not put it in URLs, logs, or persistent browser storage.

Members

NameTypeDescription
capabilityreadonly stringOpaque encrypted bearer capability.
expiresAtreadonly numberCapability expiry as Unix milliseconds.
queryFingerprintreadonly stringStable identity used to prevent accidentally renewing a different query.

TypedRawSqlParameter

interface TypedRawSqlParameter extends PreparedLiveQueryParameter

A raw SQL parameter with an explicit PostgreSQL text encoder and type hint.

Members

NameTypeDescription
typeOidreadonly numberPostgreSQL type OID hint, or 0 to request SQL-context inference.
valuereadonly string | nullPostgreSQL text-format value, or null for SQL NULL.

RawSqlParameter

type RawSqlParameter = string | number | boolean | bigint | null | TypedRawSqlParameter

A JavaScript value accepted as a PostgreSQL text-format parameter.

RealtimeAdapterSource

type RealtimeAdapterSource = "drizzle" | "kysely" | "custom"

Bounded query-builder family recorded in encrypted capabilities.

pgParam

const pgParam: PostgresParameterHelpers

Helpers for values whose PostgreSQL text encoding or type is ambiguous.

Client

Import the Client module from @neon/realtime/client. It runs in the browser, where it subscribes to sealed queries over one shared WebSocket and keeps their results up to date. It's taught in the Subscribing to queries guide.

Create one client for your app, then subscribe to a sealed query from your backend:

import { createRealtimeClient } from "@neon/realtime/client"

const client = createRealtimeClient({ url: import.meta.env.VITE_NEON_REALTIME_URL })
const subscription = client.subscribe(sealedQuery)
subscription.onChange(({ data, status }) => render(data, status))

Pass a logLevel to see what the client is doing, as Log client diagnostics shows.

React Native

The client also runs in React Native apps, with @neon/realtime 0.1.2 or later. Import it from @neon/realtime/client as usual.

React Native's WebSocket sends an Origin header derived from the Realtime endpoint. If your branch restricts Realtime to specific origins, pass a webSocketFactory that sends one of the allowed origins:

const client = createRealtimeClient({
  url: realtimeUrl,
  webSocketFactory: (url, protocols) =>
    new WebSocket(url, protocols, {
      headers: { origin: "https://app.example.com" },
    }),
})

The third WebSocket argument is a React Native extension and isn't available in browsers. An origin allowlist protects browser apps only. A native app can send any origin, so don't rely on it to authenticate native clients.

Renewing sealed queries

Most apps pass a refreshQuery function to the React or TanStack DB bindings, which renew for them. To renew a subscription yourself, see Renew the sealed query. Integration authors can build on QueryRefreshController.

Import specifier @neon/realtime/client

Symbols

SymbolKindSummary
createRealtimeClientFunctionCreate a reusable client that lazily opens and multiplexes a Realtime WebSocket connection that is bound by its first accepted query capability. The connection carries no user session credential; each subscription sends its own short-lived sealed query. Idle connections are heartbeat-probed, and recoverable disconnects retry with capped jittered backoff until the connection recovers or the client is closed.
defineParsersFunctionDefine an OID-keyed parser preset with contextual input types. OID pgTypeOids.bytea receives Uint8Array; every other OID receives PostgreSQL text. The returned object is a frozen snapshot of the input.
QueryRefreshControllerClassSchedules capability refreshes for framework integrations. Most applications should supply refreshQuery to their React or TanStack DB integration instead of constructing this class. Integration authors can use it to refresh shortly before expiry and keep retrying across capability expiry or an arbitrarily long transport outage.
LiveQueryBatchInfoInterfaceMetadata for one atomically published batch of PostgreSQL transactions.
LiveQueryErrorInterfaceAn error reported by a live-query subscription.
MaterializedLiveQueryOptionsInterfaceOptions for the default materialized subscription.
MaterializedLiveQuerySubscriptionInterfaceA live-query subscription that also retains and publishes the current rows.
RawLiveQueryOptionsInterfaceOptions for a raw, non-materializing subscription.
RawLiveQueryRowInterfaceA row in a complete raw result, paired with its opaque Realtime identity.
RawLiveQuerySubscriptionInterfaceA live-query subscription that exposes ordered raw result updates.
RealtimeClientInterfaceA client that multiplexes independently disposable subscriptions.
RealtimeClientOptionsInterfaceConfiguration for a reusable Realtime browser client.
WebSocketLikeInterfaceMinimal WebSocket contract used by the Realtime client.
LiveQueryChangeType aliasA row upsert, removal, or sequential move in an atomic publication batch.
LiveQuerySnapshotType aliasMaterialized query rows paired with their atomic lifecycle state.
LiveQueryStateType aliasAtomic lifecycle state for a live-query subscription.
PostgreSQLBytesParserType aliasA parser for PostgreSQL bytea, transported as decoded bytes.
PostgreSQLParserForOidType aliasParser input selected by the fixed Realtime OID/codec mapping.
PostgreSQLParsersType aliasA sparse collection of result parsers keyed by PostgreSQL type OID.
PostgreSQLTextParserType aliasA parser for a PostgreSQL value transported with the pg_text codec.
RawLiveQueryUpdateType aliasOne authoritative raw query-result update. rows replaces the complete preceding result and invalidates its row-ID namespace. changes applies incrementally to the current result.
RealtimeLogEntryType aliasStructured client diagnostic passed to a configured logger. Narrowing on event also narrows the metadata available on the entry.
RealtimeLogEventType aliasStable name for one client diagnostic event.
RealtimeLoggerType aliasReceives structured Realtime client diagnostics.
RealtimeLogLevelType aliasClient-side diagnostic verbosity.
WebSocketFactoryType aliasCreate a WebSocket-compatible transport for the Realtime client.
nodePostgresParsersVariableCore result parsers matching familiar node-postgres/Neon Serverless values. Less-common and unknown OIDs are intentionally absent and fall back to their exact PostgreSQL text. Known built-in array OIDs are decoded recursively by the client using the active parser for their element OID.
pgTypeOidsVariableStable PostgreSQL type OIDs used by the built-in Realtime parsers.
postgresJsParsersVariableParsers that differ from the core defaults when matching Postgres.js. Spread this partial preset into the client's parsers option.
SealedLiveQueryRe-export

createRealtimeClient

function createRealtimeClient(options: RealtimeClientOptions): RealtimeClient

Create a reusable client that lazily opens and multiplexes a Realtime WebSocket connection that is bound by its first accepted query capability.

The connection carries no user session credential; each subscription sends its own short-lived sealed query. Idle connections are heartbeat-probed, and recoverable disconnects retry with capped jittered backoff until the connection recovers or the client is closed.

Returns: A client that opens its connection when the first query subscribes.

Parameters

NameTypeDescription
optionsRealtimeClientOptionsBrowser client configuration, including the proxy WebSocket URL.

Returns

RealtimeClient

defineParsers

function defineParsers(parsers: BuiltInParsers): PostgreSQLParsers

Define an OID-keyed parser preset with contextual input types.

OID pgTypeOids.bytea receives Uint8Array; every other OID receives PostgreSQL text. The returned object is a frozen snapshot of the input.

Parameters

NameTypeDescription
parsersBuiltInParsers

Returns

PostgreSQLParsers

function defineParsers(parsers: Readonly<Record<number, PostgreSQLTextParser>>): PostgreSQLParsers

Define an OID-keyed parser preset with contextual input types.

OID pgTypeOids.bytea receives Uint8Array; every other OID receives PostgreSQL text. The returned object is a frozen snapshot of the input.

Parameters

NameTypeDescription
parsersReadonly<Record<number, PostgreSQLTextParser>>

Returns

PostgreSQLParsers

QueryRefreshController

class QueryRefreshController<Row>

Schedules capability refreshes for framework integrations.

Most applications should supply refreshQuery to their React or TanStack DB integration instead of constructing this class. Integration authors can use it to refresh shortly before expiry and keep retrying across capability expiry or an arbitrarily long transport outage.

Members

NameTypeDescription
constructornew <Row>(options: QueryRefreshControllerOptions<Row>) => QueryRefreshController<Row>
currentQuery() => SealedLiveQuery<Row>Return the capability currently managed by this controller.
replaceSealedQuery(query: SealedLiveQuery<Row>) => Promise<void>Apply a replacement capability immediately and schedule its next refresh.
setRefreshCallback(refreshQuery: (() => Promise<SealedLiveQuery<Row>>) | undefined) => voidReplace the callback used to obtain a fresh capability. Passing undefined disables scheduled refreshes without stopping the controller.
setSubscription(subscription: RawLiveQuerySubscription<Row> | undefined) => voidAssociate the active subscription managed by this controller.
start() => voidStart scheduling refreshes. Calling this more than once has no effect.
stop() => voidStop scheduling refreshes and ignore any refresh already in flight.

QueryRefreshController.replaceSealedQuery

replaceSealedQuery(query: SealedLiveQuery<Row>): Promise<void>

Apply a replacement capability immediately and schedule its next refresh.

Throws: If the replacement capability belongs to a different query, or if applying it to the active subscription fails.

Parameters

NameTypeDescription
querySealedLiveQuery<Row>

LiveQueryBatchInfo

interface LiveQueryBatchInfo

Metadata for one atomically published batch of PostgreSQL transactions.

Members

NameTypeDescription
txidsreadonly string[]Exact PostgreSQL transaction IDs represented as decimal strings.

LiveQueryError

interface LiveQueryError extends Error

An error reported by a live-query subscription.

Members

NameTypeDescription
cause?unknown
codereadonly stringStable machine-readable error code.
messagestring
namestring
retryablereadonly booleanWhether reconnecting or obtaining a fresh sealed query may recover it.
sqlState?readonly stringPostgreSQL SQLSTATE supplied for an authenticated debug query failure.
stack?string

MaterializedLiveQueryOptions

interface MaterializedLiveQueryOptions<Row>

Options for the default materialized subscription.

Members

NameTypeDescription
initialData?readonly Row[]Preloaded rows exposed while connecting to the authoritative result. Supply decoded rows matching the live result, restoring any values changed by transport serialization (for example, JSON date strings) beforehand.
materialize?readonly trueSelect materialization; omitted and true are equivalent.

MaterializedLiveQuerySubscription

interface MaterializedLiveQuerySubscription<Row> extends RawLiveQuerySubscription<Row>

A live-query subscription that also retains and publishes the current rows.

Members

NameTypeDescription
awaitRows(matches: (rows: readonly Row[]) => boolean, timeout?: number) => Promise<void>Wait until the materialized rows satisfy a predicate. The current snapshot is inspected before waiting for later changes, so this also succeeds when matching rows arrived before the call.
awaitTxId(txid: string, timeout?: number) => Promise<void>Wait until this subscription has applied a PostgreSQL transaction. Recently applied transaction IDs are retained so this also succeeds when the batch arrives before the caller receives the mutation response.
getSnapshot() => LiveQuerySnapshot<Row>Return the current rows and lifecycle state atomically.
getState() => LiveQueryStateReturn the complete current lifecycle state.
onChange(listener: (snapshot: LiveQuerySnapshot<Row>) => void) => () => voidObserve row or lifecycle changes as complete snapshots. The listener runs after complete-row replacements, incremental changes, and state transitions.
onStateChange(listener: (state: LiveQueryState) => void) => () => voidObserve lifecycle transitions.
onUpdate(listener: (update: RawLiveQueryUpdate<Row>) => void) => () => voidObserve complete-row replacements and incremental changes through one ordered update stream. Every affected materialized subscription has already applied an update before its listener runs.
renew(query: SealedLiveQuery<Row>) => Promise<void>Renew this logical subscription with a capability for the same exact query. If the preceding subscription has expired, the client creates a new wire subscription while preserving this object, its listeners, and any retained rows. The replacement then produces a new authoritative result.
unsubscribe() => voidPermanently close this subscription and remove its listeners.

MaterializedLiveQuerySubscription.awaitRows

awaitRows(matches: (rows: readonly Row[]) => boolean, timeout?: number): Promise<void>

Wait until the materialized rows satisfy a predicate.

The current snapshot is inspected before waiting for later changes, so this also succeeds when matching rows arrived before the call.

Throws: If a supplied timeout elapses, the predicate throws, or the subscription closes or enters a terminal error before the rows match.

Parameters

NameTypeDescription
matches(rows: readonly Row[]) => booleanPredicate evaluated against each complete row snapshot.
timeout?numberOptional maximum wait in milliseconds. By default the promise remains pending until the rows match or the subscription closes.

MaterializedLiveQuerySubscription.awaitTxId

awaitTxId(txid: string, timeout?: number): Promise<void>

Wait until this subscription has applied a PostgreSQL transaction.

Recently applied transaction IDs are retained so this also succeeds when the batch arrives before the caller receives the mutation response.

Remarks: This does not determine whether a transaction committed, so pass only IDs from transactions known to have committed.

Throws: If the timeout elapses, the transaction ID is invalid, or the subscription fails or closes before applying the transaction.

Parameters

NameTypeDescription
txidstringPostgreSQL transaction ID as a decimal string.
timeout?numberOptional maximum wait in milliseconds. By default the promise remains pending until the transaction arrives, the subscription fails, or the subscription closes.

MaterializedLiveQuerySubscription.onChange

onChange(listener: (snapshot: LiveQuerySnapshot<Row>) => void): () => void

Observe row or lifecycle changes as complete snapshots. The listener runs after complete-row replacements, incremental changes, and state transitions.

Returns: A function that removes this listener.

Parameters

NameTypeDescription
listener(snapshot: LiveQuerySnapshot<Row>) => void

MaterializedLiveQuerySubscription.onStateChange

onStateChange(listener: (state: LiveQueryState) => void): () => void

Observe lifecycle transitions.

Returns: A function that removes this listener.

Parameters

NameTypeDescription
listener(state: LiveQueryState) => void

MaterializedLiveQuerySubscription.onUpdate

onUpdate(listener: (update: RawLiveQueryUpdate<Row>) => void): () => void

Observe complete-row replacements and incremental changes through one ordered update stream. Every affected materialized subscription has already applied an update before its listener runs.

Returns: A function that removes this listener.

Parameters

NameTypeDescription
listener(update: RawLiveQueryUpdate<Row>) => void

MaterializedLiveQuerySubscription.renew

renew(query: SealedLiveQuery<Row>): Promise<void>

Renew this logical subscription with a capability for the same exact query. If the preceding subscription has expired, the client creates a new wire subscription while preserving this object, its listeners, and any retained rows. The replacement then produces a new authoritative result.

Returns: A promise that resolves after the proxy accepts the replacement. Calling this while stale moves the subscription to connecting; a subsequent authoritative result returns it to live.

Throws: If the replacement query fingerprint differs or renewal is rejected.

Parameters

NameTypeDescription
querySealedLiveQuery<Row>

RawLiveQueryOptions

interface RawLiveQueryOptions

Options for a raw, non-materializing subscription.

Members

NameTypeDescription
materializereadonly falseDisable SDK materialization and consume raw result updates directly.

RawLiveQueryRow

interface RawLiveQueryRow<Row>

A row in a complete raw result, paired with its opaque Realtime identity.

Members

NameTypeDescription
rowreadonly RowDecoded query row.
rowIdreadonly stringOpaque identity invalidated by the next complete rows update.

RawLiveQuerySubscription

interface RawLiveQuerySubscription<Row>

A live-query subscription that exposes ordered raw result updates.

Members

NameTypeDescription
awaitTxId(txid: string, timeout?: number) => Promise<void>Wait until this subscription has applied a PostgreSQL transaction. Recently applied transaction IDs are retained so this also succeeds when the batch arrives before the caller receives the mutation response.
getState() => LiveQueryStateReturn the complete current lifecycle state.
onStateChange(listener: (state: LiveQueryState) => void) => () => voidObserve lifecycle transitions.
onUpdate(listener: (update: RawLiveQueryUpdate<Row>) => void) => () => voidObserve complete-row replacements and incremental changes through one ordered update stream. Every affected materialized subscription has already applied an update before its listener runs.
renew(query: SealedLiveQuery<Row>) => Promise<void>Renew this logical subscription with a capability for the same exact query. If the preceding subscription has expired, the client creates a new wire subscription while preserving this object, its listeners, and any retained rows. The replacement then produces a new authoritative result.
unsubscribe() => voidPermanently close this subscription and remove its listeners.

RawLiveQuerySubscription.awaitTxId

awaitTxId(txid: string, timeout?: number): Promise<void>

Wait until this subscription has applied a PostgreSQL transaction.

Recently applied transaction IDs are retained so this also succeeds when the batch arrives before the caller receives the mutation response.

Remarks: This does not determine whether a transaction committed, so pass only IDs from transactions known to have committed.

Throws: If the timeout elapses, the transaction ID is invalid, or the subscription fails or closes before applying the transaction.

Parameters

NameTypeDescription
txidstringPostgreSQL transaction ID as a decimal string.
timeout?numberOptional maximum wait in milliseconds. By default the promise remains pending until the transaction arrives, the subscription fails, or the subscription closes.

RawLiveQuerySubscription.onStateChange

onStateChange(listener: (state: LiveQueryState) => void): () => void

Observe lifecycle transitions.

Returns: A function that removes this listener.

Parameters

NameTypeDescription
listener(state: LiveQueryState) => void

RawLiveQuerySubscription.onUpdate

onUpdate(listener: (update: RawLiveQueryUpdate<Row>) => void): () => void

Observe complete-row replacements and incremental changes through one ordered update stream. Every affected materialized subscription has already applied an update before its listener runs.

Returns: A function that removes this listener.

Parameters

NameTypeDescription
listener(update: RawLiveQueryUpdate<Row>) => void

RawLiveQuerySubscription.renew

renew(query: SealedLiveQuery<Row>): Promise<void>

Renew this logical subscription with a capability for the same exact query. If the preceding subscription has expired, the client creates a new wire subscription while preserving this object, its listeners, and any retained rows. The replacement then produces a new authoritative result.

Returns: A promise that resolves after the proxy accepts the replacement. Calling this while stale moves the subscription to connecting; a subsequent authoritative result returns it to live.

Throws: If the replacement query fingerprint differs or renewal is rejected.

Parameters

NameTypeDescription
querySealedLiveQuery<Row>

RealtimeClient

interface RealtimeClient

A client that multiplexes independently disposable subscriptions.

Members

NameTypeDescription
close() => voidPermanently close all subscriptions and the underlying WebSocket.
subscribe<Row>(query: SealedLiveQuery<Row>, options?: MaterializedLiveQueryOptions<NoInferCompat<Row>>) => MaterializedLiveQuerySubscription<Row> & <Row>(query: SealedLiveQuery<Row>, options: RawLiveQueryOptions) => RawLiveQuerySubscription<Row>Start a materialized subscription, optionally with preloaded rows.

RealtimeClient.subscribe

subscribe<Row>(query: SealedLiveQuery<Row>, options?: MaterializedLiveQueryOptions<NoInferCompat<Row>>): MaterializedLiveQuerySubscription<Row>

Start a materialized subscription, optionally with preloaded rows.

Returns: An independently disposable materialized subscription.

Throws: If the query is malformed or the client is closed.

Parameters

NameTypeDescription
querySealedLiveQuery<Row>Short-lived capability returned by the application backend.
options?MaterializedLiveQueryOptions<NoInferCompat<Row>>Materialization and optional preloaded-row settings.
subscribe<Row>(query: SealedLiveQuery<Row>, options: RawLiveQueryOptions): RawLiveQuerySubscription<Row>

Start a raw subscription without retaining query rows in the SDK.

Returns: An independently disposable raw subscription.

Throws: If the query is malformed or the client is closed.

Parameters

NameTypeDescription
querySealedLiveQuery<Row>Short-lived capability returned by the application backend.
optionsRawLiveQueryOptionsSet materialize to false to consume raw events.

RealtimeClientOptions

interface RealtimeClientOptions

Configuration for a reusable Realtime browser client.

Members

NameTypeDescription
logger?readonly RealtimeLoggerStructured diagnostic sink. It is called only for events enabled by logLevel; exceptions from the sink are ignored. Server-issued client warnings do not use this sink.
logLevel?readonly RealtimeLogLevelMinimum client diagnostic level. The default, silent, emits no structured diagnostics. Server-issued client warnings are always written to console.error independently of this setting. When enabled without logger, entries are written to console.
parsers?readonly Readonly<Record<number, PostgreSQLBytesParser<unknown> | PostgreSQLTextParser<unknown>> & BuiltInParsers>PostgreSQL result parsers keyed by type OID. These entries override nodePostgresParsers. The client snapshots the object when it is created, so later mutations have no effect.
urlreadonly stringRealtime proxy WebSocket URL, using wss: outside local development.
webSocketFactory?readonly WebSocketFactoryOverride how the client creates its WebSocket. This is primarily useful in runtimes such as React Native, whose WebSocket constructor accepts platform-specific connection options. In browsers, omit this option to use the built-in WebSocket constructor.

WebSocketLike

interface WebSocketLike

Minimal WebSocket contract used by the Realtime client.

Members

NameTypeDescription
readyStatereadonly number
addEventListener(type: "open", listener: () => void) => void & (type: "message", listener: (event: { readonly data: unknown }) => void) => void & (type: "close", listener: () => void) => void & (type: "error", listener: () => void) => void
close(code?: number, reason?: string) => void
send(data: string) => void
terminate?() => voidImmediately destroy the transport when the implementation supports it.

LiveQueryChange

type LiveQueryChange<Row> = { readonly row: Row; readonly rowId: string; readonly type: "upsert" } | { readonly rowId: string; readonly type: "remove" } | { readonly afterRowId: string | null; readonly rowId: string; readonly type: "move" }

A row upsert, removal, or sequential move in an atomic publication batch.

LiveQuerySnapshot

type LiveQuerySnapshot<Row> = LiveQueryState & { data: readonly Row[] | undefined }

Materialized query rows paired with their atomic lifecycle state.

LiveQueryState

type LiveQueryState = { readonly error: undefined; readonly status: "connecting" | "live" | "stale" | "closed" } | { readonly error: LiveQueryError; readonly status: "error" }

Atomic lifecycle state for a live-query subscription.

PostgreSQLBytesParser

type PostgreSQLBytesParser<Value = unknown> = (value: Uint8Array) => Value

A parser for PostgreSQL bytea, transported as decoded bytes.

PostgreSQLParserForOid

type PostgreSQLParserForOid<Oid extends number> = Oid extends typeof pgTypeOids.bytea ? PostgreSQLBytesParser : PostgreSQLTextParser

Parser input selected by the fixed Realtime OID/codec mapping.

PostgreSQLParsers

type PostgreSQLParsers = Readonly<Record<number, PostgreSQLTextParser | PostgreSQLBytesParser> & BuiltInParsers>

A sparse collection of result parsers keyed by PostgreSQL type OID.

PostgreSQLTextParser

type PostgreSQLTextParser<Value = unknown> = (value: string) => Value

A parser for a PostgreSQL value transported with the pg_text codec.

RawLiveQueryUpdate

type RawLiveQueryUpdate<Row> = { rows: readonly RawLiveQueryRow<Row>[]; readonly type: "rows" } | { readonly batch: LiveQueryBatchInfo; changes: readonly LiveQueryChange<Row>[]; readonly type: "changes" }

One authoritative raw query-result update.

rows replaces the complete preceding result and invalidates its row-ID namespace. changes applies incrementally to the current result.

RealtimeLogEntry

type RealtimeLogEntry = { [Event in RealtimeLogEvent]: RealtimeLogEntryFor<Event> }[RealtimeLogEvent]

Structured client diagnostic passed to a configured logger.

Narrowing on event also narrows the metadata available on the entry.

RealtimeLogEvent

type RealtimeLogEvent = keyof RealtimeLogEventDefinition

Stable name for one client diagnostic event.

RealtimeLogger

type RealtimeLogger = (entry: RealtimeLogEntry) => void

Receives structured Realtime client diagnostics.

RealtimeLogLevel

type RealtimeLogLevel = "silent" | "error" | "warn" | "info" | "debug"

Client-side diagnostic verbosity.

WebSocketFactory

type WebSocketFactory = (url: string, protocols: string | string[]) => WebSocketLike

Create a WebSocket-compatible transport for the Realtime client.

nodePostgresParsers

const nodePostgresParsers: PostgreSQLParsers

Core result parsers matching familiar node-postgres/Neon Serverless values.

Less-common and unknown OIDs are intentionally absent and fall back to their exact PostgreSQL text. Known built-in array OIDs are decoded recursively by the client using the active parser for their element OID.

pgTypeOids

const pgTypeOids: Readonly<{ readonly bit: 1560; readonly bitArray: 1561; readonly bool: 16; readonly boolArray: 1000; readonly box: 603; readonly boxArray: 1020; readonly bpchar: 1042; readonly bpcharArray: 1014; readonly bytea: 17; readonly byteaArray: 1001; readonly char: 18; readonly charArray: 1002; readonly cidr: 650; readonly cidrArray: 651; readonly circle: 718; readonly circleArray: 719; readonly cstring: 2275; readonly cstringArray: 1263; readonly date: 1082; readonly dateArray: 1182; readonly float4: 700; readonly float4Array: 1021; readonly float8: 701; readonly float8Array: 1022; readonly inet: 869; readonly inetArray: 1041; readonly int2: 21; readonly int2Array: 1005; readonly int4: 23; readonly int4Array: 1007; readonly int8: 20; readonly int8Array: 1016; readonly interval: 1186; readonly intervalArray: 1187; readonly json: 114; readonly jsonArray: 199; readonly jsonb: 3802; readonly jsonbArray: 3807; readonly line: 628; readonly lineArray: 629; readonly lseg: 601; readonly lsegArray: 1018; readonly macaddr: 829; readonly macaddr8: 774; readonly macaddr8Array: 775; readonly macaddrArray: 1040; readonly money: 790; readonly moneyArray: 791; readonly name: 19; readonly nameArray: 1003; readonly numeric: 1700; readonly numericArray: 1231; readonly oid: 26; readonly oidArray: 1028; readonly path: 602; readonly pathArray: 1019; readonly pgLsn: 3220; readonly pgLsnArray: 3221; readonly point: 600; readonly pointArray: 1017; readonly polygon: 604; readonly polygonArray: 1027; readonly text: 25; readonly textArray: 1009; readonly time: 1083; readonly timeArray: 1183; readonly timestamp: 1114; readonly timestampArray: 1115; readonly timestamptz: 1184; readonly timestamptzArray: 1185; readonly timetz: 1266; readonly timetzArray: 1270; readonly uuid: 2950; readonly uuidArray: 2951; readonly varbit: 1562; readonly varbitArray: 1563; readonly varchar: 1043; readonly varcharArray: 1015; readonly xml: 142; readonly xmlArray: 143 }>

Stable PostgreSQL type OIDs used by the built-in Realtime parsers.

postgresJsParsers

const postgresJsParsers: PostgreSQLParsers

Parsers that differ from the core defaults when matching Postgres.js. Spread this partial preset into the client's parsers option.

SealedLiveQuery

Re-exported from Backend.

React

Import the React bindings from @neon/realtime-react. They run in your React frontend: RealtimeProvider shares one client, useLiveQuery subscribes a component to a sealed query, and useRealtimeClient returns the shared client. They're taught in the React section of the reactivity guide.

Import specifier @neon/realtime-react

Symbols

SymbolKindSummary
RealtimeProviderFunctionProvide one shared Realtime client to descendant useLiveQuery and useRealtimeClient hooks. Create the client once for the browser application. The provider does not fetch sealed queries or close the client when it unmounts.
useLiveQueryFunctionSubscribe to a sealed query and expose its materialized snapshot to React. The hook owns subscription cleanup.
useRealtimeClientFunctionRead the shared Realtime client from the nearest RealtimeProvider. Use it alongside useLiveQuery when a component needs the client itself: to pass it to realtimeCollectionOptions() from @neon/realtime-tanstack, or to call subscribe() with a sealed query directly. Subscriptions opened through subscribe() are not owned by React, so call unsubscribe() when they are no longer needed.
RealtimeProviderPropsInterfaceProps accepted by RealtimeProvider.
UseLiveQueryOptionsInterfaceOptions for useLiveQuery.
UseLiveQueryResultType aliasReact-facing snapshot and lower-level utilities returned by useLiveQuery().
UseLiveQueryUtilsType aliasStable imperative access to the hook's underlying materialized subscription. Cleanup remains owned by React, so unsubscribe() is intentionally omitted.

RealtimeProvider

function RealtimeProvider(props: RealtimeProviderProps): ReactElement

Provide one shared Realtime client to descendant useLiveQuery and useRealtimeClient hooks.

Create the client once for the browser application. The provider does not fetch sealed queries or close the client when it unmounts.

Returns: A context provider for Realtime hooks.

Parameters

NameTypeDescription
propsRealtimeProviderPropsShared client and descendant React tree.

Returns

ReactElement

useLiveQuery

function useLiveQuery<Row>(query: SealedLiveQuery<Row>, options: UseLiveQueryOptions<NoInferCompat<Row>> = {}): UseLiveQueryResult<Row>

Subscribe to a sealed query and expose its materialized snapshot to React. The hook owns subscription cleanup.

Returns: The current rows and lifecycle state plus stable subscription utilities.

Throws: If used outside a RealtimeProvider.

Type parameters

NameDefaultDescription
RowRow inferred from the query.

Parameters

NameTypeDescription
querySealedLiveQuery<Row>Capability obtained from the application backend.
optionsUseLiveQueryOptions<NoInferCompat<Row>>Optional preloaded rows and capability-refresh callback.

Returns

UseLiveQueryResult<Row>

useRealtimeClient

function useRealtimeClient(): RealtimeClient

Read the shared Realtime client from the nearest RealtimeProvider.

Use it alongside useLiveQuery when a component needs the client itself: to pass it to realtimeCollectionOptions() from @neon/realtime-tanstack, or to call subscribe() with a sealed query directly. Subscriptions opened through subscribe() are not owned by React, so call unsubscribe() when they are no longer needed.

Returns: The client passed to the nearest provider.

Throws: If used outside a RealtimeProvider.

Example

import type { SealedLiveQuery } from "@neon/realtime/client";
import { useRealtimeClient } from "@neon/realtime-react";
import { realtimeCollectionOptions } from "@neon/realtime-tanstack";
import { createCollection } from "@tanstack/db";
import { useMemo } from "react";

interface Todo {
  id: string;
  title: string;
}

function useTodos(query: SealedLiveQuery<Todo>) {
  const client = useRealtimeClient();
  return useMemo(
    () =>
      createCollection(realtimeCollectionOptions({
        client,
        query,
        getKey: (todo) => todo.id,
      })),
    [client, query],
  );
}

Returns

RealtimeClient

RealtimeProviderProps

interface RealtimeProviderProps

Props accepted by RealtimeProvider.

Members

NameTypeDescription
childrenreadonly ReactNodeReact subtree that may call useLiveQuery or useRealtimeClient.
clientreadonly RealtimeClientShared browser client made available to descendant hooks.

UseLiveQueryOptions

interface UseLiveQueryOptions<Row>

Options for useLiveQuery.

Members

NameTypeDescription
initialData?readonly Row[]Decoded rows exposed immediately, including during server rendering. Restore values changed by transport serialization before passing them here.
refreshQuery?readonly () => Promise<SealedLiveQuery<Row>>Obtain a replacement capability for the same exact query before expiry. Transient failures are retried while the current capability remains valid.

UseLiveQueryResult

type UseLiveQueryResult<Row> = LiveQuerySnapshot<Row> & { readonly utils: UseLiveQueryUtils<Row> }

React-facing snapshot and lower-level utilities returned by useLiveQuery().

UseLiveQueryUtils

type UseLiveQueryUtils<Row> = Omit<MaterializedLiveQuerySubscription<Row>, "unsubscribe">

Stable imperative access to the hook's underlying materialized subscription.

Cleanup remains owned by React, so unsubscribe() is intentionally omitted.

TanStack DB

Import the TanStack DB adapter from @neon/realtime-tanstack. It runs in the browser, where realtimeCollectionOptions turns a sealed query into a TanStack DB collection. It's taught in the TanStack DB section of the reactivity guide. The mutations guide covers optimistic writes, and the SSR guide covers hydration.

Import specifier @neon/realtime-tanstack

Symbols

SymbolKindSummary
realtimeCollectionOptionsFunctionCreate TanStack DB collection options backed by a raw live-query subscription. Complete-row replacements and committed change batches are applied atomically. This is an unordered keyed collection: move operations do not change membership or values and are ignored. Use core materialized subscriptions for server order.
RealtimeCollectionConfigInterfaceConfiguration for a Realtime-backed TanStack DB collection. The adapter owns sync, uses eager synchronization, and supplies its own collection utilities.
RealtimeCollectionUtilsInterfaceUtilities attached to a Realtime-backed TanStack DB collection.
RealtimeCollectionOptionsType aliasTanStack DB collection options produced by realtimeCollectionOptions.

realtimeCollectionOptions

function realtimeCollectionOptions<Row extends object, Key extends string | number = string | number, Schema extends StandardSchemaV1<unknown, unknown> = never>(config: RealtimeCollectionConfig<NoInferCompat<Row>, Key, Schema> & { readonly query: SealedLiveQuery<Row> }): RealtimeCollectionOptions<Row, Key, Schema>

Create TanStack DB collection options backed by a raw live-query subscription. Complete-row replacements and committed change batches are applied atomically. This is an unordered keyed collection: move operations do not change membership or values and are ignored. Use core materialized subscriptions for server order.

Returns: Collection options to pass to TanStack DB's createCollection().

Type parameters

NameDefaultDescription
RowObject row synchronized into the collection.
Keystring | numberStable key returned by getKey.
SchemaneverOptional Standard Schema used by TanStack DB.

Parameters

NameTypeDescription
configRealtimeCollectionConfig<NoInferCompat<Row>, Key, Schema> & { readonly query: SealedLiveQuery<Row> }Live-query subscription settings and ordinary TanStack DB collection options.

Returns

RealtimeCollectionOptions<Row, Key, Schema>

RealtimeCollectionConfig

interface RealtimeCollectionConfig<Row extends object, Key extends string | number = string | number, Schema extends StandardSchemaV1 = never> extends Omit<BaseCollectionConfig<Row, Key, Schema, RealtimeCollectionUtils, void>, "syncMode" | "utils">

Configuration for a Realtime-backed TanStack DB collection.

The adapter owns sync, uses eager synchronization, and supplies its own collection utilities.

Members

NameTypeDescription
autoIndex?"off" | "eager"Auto-indexing mode for the collection. When enabled, indexes will be automatically created for simple where expressions.
clientreadonly RealtimeClientReusable low-level Realtime client.
compare?(x: Row, y: Row) => numberOptional function to compare two items. This is used to order the items in the collection.
defaultIndexType?IndexConstructor<Key>Default index type to use when creating indexes without an explicit type. Required for auto-indexing. Import from '@tanstack/db'.
defaultStringCollation?StringCollationConfigSpecifies how to compare data in the collection. This should be configured to match data ordering on the backend. E.g., when using the Electric DB collection these options should match the database's collation settings.
gcTime?numberTime in milliseconds after which the collection will be garbage collected when it has no active subscribers. Defaults to 5 minutes (300000ms).
getKeyreadonly (row: Row) => KeyDerive the stable unique TanStack DB key for a row.
id?string
onDelete?DeleteMutationFn<Row, Key, RealtimeCollectionUtils, void>Optional asynchronous handler function called before a delete operation
onInsert?InsertMutationFn<Row, Key, RealtimeCollectionUtils, void>Optional asynchronous handler function called before an insert operation
onUpdate?UpdateMutationFn<Row, Key, RealtimeCollectionUtils, void>Optional asynchronous handler function called before an update operation
queryreadonly SealedLiveQuery<Row>Initial query for the exact query backing this collection.
refreshQuery?readonly () => Promise<SealedLiveQuery<Row>>Obtain a replacement capability for the same exact query before expiry. Transient failures are retried while the current capability remains valid.
schema?Schema
startSync?booleanWhether to eagerly start syncing on collection creation. When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches. Note: Even with startSync=true, collections will pause syncing when there are no active subscribers (typically when components querying the collection unmount), resuming when new subscribers attach. This preserves normal staleTime/gcTime behavior.

RealtimeCollectionConfig.autoIndex

autoIndex?: "off" | "eager"

Auto-indexing mode for the collection. When enabled, indexes will be automatically created for simple where expressions.

Default

"off"
  • "off": No automatic indexing (default). Use explicit indexes for better bundle size.
  • "eager": Automatically create indexes for simple where expressions in subscribeChanges. Requires setting defaultIndexType.

RealtimeCollectionConfig.compare

compare?: (x: Row, y: Row) => number

Optional function to compare two items. This is used to order the items in the collection.

Example

// For a collection with a 'createdAt' field
compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()

RealtimeCollectionConfig.defaultIndexType

defaultIndexType?: IndexConstructor<Key>

Default index type to use when creating indexes without an explicit type. Required for auto-indexing. Import from '@tanstack/db'.

Example

import { BasicIndex } from '@tanstack/db'
const collection = createCollection({
  defaultIndexType: BasicIndex,
  autoIndex: 'eager',
  // ...
})

RealtimeCollectionConfig.onDelete

onDelete?: DeleteMutationFn<Row, Key, RealtimeCollectionUtils, void>

Optional asynchronous handler function called before a delete operation

Parameter params: Object containing transaction and collection information

Returns: Promise resolving to any value

Example

// Basic delete handler
onDelete: async ({ transaction, collection }) => {
  const deletedKey = transaction.mutations[0].key
  await api.deleteTodo(deletedKey)
}

Example

// Delete handler with multiple items
onDelete: async ({ transaction, collection }) => {
  const keysToDelete = transaction.mutations.map(m => m.key)
  await api.deleteTodos(keysToDelete)
}

Example

// Delete handler with confirmation
onDelete: async ({ transaction, collection }) => {
  const mutation = transaction.mutations[0]
  const shouldDelete = await confirmDeletion(mutation.original)
  if (!shouldDelete) {
    throw new Error('Delete cancelled by user')
  }
  await api.deleteTodo(mutation.original.id)
}

Example

// Delete handler with optimistic rollback
onDelete: async ({ transaction, collection }) => {
  const mutation = transaction.mutations[0]
  try {
    await api.deleteTodo(mutation.original.id)
  } catch (error) {
    // Transaction will automatically rollback optimistic changes
    console.error('Delete failed, rolling back:', error)
    throw error
  }
}

RealtimeCollectionConfig.onInsert

onInsert?: InsertMutationFn<Row, Key, RealtimeCollectionUtils, void>

Optional asynchronous handler function called before an insert operation

Parameter params: Object containing transaction and collection information

Returns: Promise resolving to any value

Example

// Basic insert handler
onInsert: async ({ transaction, collection }) => {
  const newItem = transaction.mutations[0].modified
  await api.createTodo(newItem)
}

Example

// Insert handler with multiple items
onInsert: async ({ transaction, collection }) => {
  const items = transaction.mutations.map(m => m.modified)
  await api.createTodos(items)
}

Example

// Insert handler with error handling
onInsert: async ({ transaction, collection }) => {
  try {
    const newItem = transaction.mutations[0].modified
    const result = await api.createTodo(newItem)
    return result
  } catch (error) {
    console.error('Insert failed:', error)
    throw error // This will cause the transaction to fail
  }
}

Example

// Insert handler with metadata
onInsert: async ({ transaction, collection }) => {
  const mutation = transaction.mutations[0]
  await api.createTodo(mutation.modified, {
    source: mutation.metadata?.source,
    timestamp: mutation.createdAt
  })
}

RealtimeCollectionConfig.onUpdate

onUpdate?: UpdateMutationFn<Row, Key, RealtimeCollectionUtils, void>

Optional asynchronous handler function called before an update operation

Parameter params: Object containing transaction and collection information

Returns: Promise resolving to any value

Example

// Basic update handler
onUpdate: async ({ transaction, collection }) => {
  const updatedItem = transaction.mutations[0].modified
  await api.updateTodo(updatedItem.id, updatedItem)
}

Example

// Update handler with partial updates
onUpdate: async ({ transaction, collection }) => {
  const mutation = transaction.mutations[0]
  const changes = mutation.changes // Only the changed fields
  await api.updateTodo(mutation.original.id, changes)
}

Example

// Update handler with multiple items
onUpdate: async ({ transaction, collection }) => {
  const updates = transaction.mutations.map(m => ({
    id: m.key,
    changes: m.changes
  }))
  await api.updateTodos(updates)
}

Example

// Update handler with optimistic rollback
onUpdate: async ({ transaction, collection }) => {
  const mutation = transaction.mutations[0]
  try {
    await api.updateTodo(mutation.original.id, mutation.changes)
  } catch (error) {
    // Transaction will automatically rollback optimistic changes
    console.error('Update failed, rolling back:', error)
    throw error
  }
}

RealtimeCollectionConfig.startSync

startSync?: boolean

Whether to eagerly start syncing on collection creation. When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.

Note: Even with startSync=true, collections will pause syncing when there are no active subscribers (typically when components querying the collection unmount), resuming when new subscribers attach. This preserves normal staleTime/gcTime behavior.

Default

false

RealtimeCollectionUtils

interface RealtimeCollectionUtils extends UtilsRecord

Utilities attached to a Realtime-backed TanStack DB collection.

Members

NameTypeDescription
awaitTxId(txid: string, timeout?: number) => Promise<boolean>Wait until this query has processed a known committed PostgreSQL transaction. Covered row changes enter TanStack DB's causal sync queue before this resolves.
[key: string]any

RealtimeCollectionUtils.awaitTxId

awaitTxId(txid: string, timeout?: number): Promise<boolean>

Wait until this query has processed a known committed PostgreSQL transaction. Covered row changes enter TanStack DB's causal sync queue before this resolves.

Remarks: This does not determine whether a transaction committed, so pass only IDs from transactions known to have committed.

Throws: If a supplied timeout elapses or the collection is cleaned up.

Parameters

NameTypeDescription
txidstringPostgreSQL transaction ID as a decimal string.
timeout?numberOptional maximum wait in milliseconds. By default, the promise remains pending until the transaction arrives or the collection is cleaned up.

RealtimeCollectionOptions

type RealtimeCollectionOptions<Row extends object, Key extends string | number, Schema extends StandardSchemaV1> = Omit<CollectionConfig<Row, Key, Schema, RealtimeCollectionUtils>, "utils"> & { readonly utils: RealtimeCollectionUtils }

TanStack DB collection options produced by realtimeCollectionOptions.

Drizzle

Import the Drizzle adapter from @neon/realtime-drizzle. It runs on your server: pass drizzleAdapter() as the adapter option to createRealtime(), then seal Drizzle selects like any other query. It's taught in Using a query builder or ORM, and the Drizzle example goes further.

Import specifier @neon/realtime-drizzle

Symbols

SymbolKindSummary
drizzleAdapterFunctionPrepare concrete Drizzle PostgreSQL selects as live queries. Drizzle supplies parameterized SQL and driver-ready values. Every parameter uses OID 0, allowing PostgreSQL to infer its type from SQL context. The proxy returns result metadata when it accepts the subscription.

drizzleAdapter

function drizzleAdapter(): RealtimeAdapter<ConcretePgSelectQuery>

Prepare concrete Drizzle PostgreSQL selects as live queries.

Drizzle supplies parameterized SQL and driver-ready values. Every parameter uses OID 0, allowing PostgreSQL to infer its type from SQL context. The proxy returns result metadata when it accepts the subscription.

Returns: An adapter to pass to createRealtime() on the application backend.

Returns

RealtimeAdapter<ConcretePgSelectQuery>

Drizzle client

Import drizzleParsers from @neon/realtime-drizzle/client. It runs in the browser: spread it into the client's parsers option so dates and timestamps decode the way Drizzle decodes them. The Drizzle example shows it in use.

Import specifier @neon/realtime-drizzle/client

Symbols

SymbolKindSummary
drizzleParsersVariableParser overrides for Drizzle-compatible hydrated values. PostgreSQL date remains a string and zone-less timestamp is interpreted as UTC, matching Drizzle's default PostgreSQL column modes. Spread this preset into createRealtimeClient({ parsers }). Per-column Drizzle modes are intentionally outside this OID-only compatibility layer.

drizzleParsers

const drizzleParsers: PostgreSQLParsers

Parser overrides for Drizzle-compatible hydrated values.

PostgreSQL date remains a string and zone-less timestamp is interpreted as UTC, matching Drizzle's default PostgreSQL column modes. Spread this preset into createRealtimeClient({ parsers }). Per-column Drizzle modes are intentionally outside this OID-only compatibility layer.

Kysely

Import the Kysely adapter from @neon/realtime-kysely. It runs on your server: pass kyselyAdapter() as the adapter option to createRealtime(), then seal Kysely selects like any other query. It's taught in Using a query builder or ORM, and the Kysely example goes further.

Import specifier @neon/realtime-kysely

Symbols

SymbolKindSummary
kyselyAdapterFunctionPrepare concrete Kysely selects as live queries. The adapter compiles Kysely's operation tree with its PostgreSQL compiler, then encodes the raw parameters using node-postgres-compatible rules. It never connects to or executes against the configured Kysely database.

kyselyAdapter

function kyselyAdapter(): RealtimeAdapter<KyselySelectQuery>

Prepare concrete Kysely selects as live queries.

The adapter compiles Kysely's operation tree with its PostgreSQL compiler, then encodes the raw parameters using node-postgres-compatible rules. It never connects to or executes against the configured Kysely database.

Returns: An adapter to pass to createRealtime() on the application backend.

Returns

RealtimeAdapter<KyselySelectQuery>

Last updated on

Was this page helpful?
Edit on GitHub