> This page location: Realtime > SDKs > TypeScript > Client
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

> Summary: Reference for the Realtime Client module, @neon/realtime/client, which subscribes to sealed live queries over one shared WebSocket, materializes their results and runs in browsers and React Native.

# TypeScript SDK: Client

Subscribe to sealed queries from the browser with @neon/realtime/client

Last updated: 2026-11-18

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](https://neon.com/docs/realtime/guides/subscribing) guide.

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

```ts
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](https://neon.com/docs/realtime/guides/subscribing#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:

```ts
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](https://neon.com/docs/realtime/guides/reactivity), which renew for them. To renew a subscription yourself, see [Renew the sealed query](https://neon.com/docs/realtime/guides/subscribing#renew-the-sealed-query). Integration authors can build on [`QueryRefreshController`](https://neon.com/docs/realtime/sdks/typescript/client#client-queryrefreshcontroller).

## API reference

**Import specifier** `@neon/realtime/client`

### Symbols

| Symbol | Kind | Summary |
| - | - | - |
| [`createRealtimeClient`](https://neon.com/docs/realtime/sdks/typescript/client#client-createrealtimeclient) | Function | 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. |
| [`defineParsers`](https://neon.com/docs/realtime/sdks/typescript/client#client-defineparsers) | Function | 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. |
| [`QueryRefreshController`](https://neon.com/docs/realtime/sdks/typescript/client#client-queryrefreshcontroller) | Class | 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. |
| [`LiveQueryBatchInfo`](https://neon.com/docs/realtime/sdks/typescript/client#client-livequerybatchinfo) | Interface | Metadata for one atomically published batch of PostgreSQL transactions. |
| [`LiveQueryError`](https://neon.com/docs/realtime/sdks/typescript/client#client-livequeryerror) | Interface | An error reported by a live-query subscription. |
| [`MaterializedLiveQueryOptions`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequeryoptions) | Interface | Options for the default materialized subscription. |
| [`MaterializedLiveQuerySubscription`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequerysubscription) | Interface | A live-query subscription that also retains and publishes the current rows. |
| [`RawLiveQueryOptions`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequeryoptions) | Interface | Options for a raw, non-materializing subscription. |
| [`RawLiveQueryRow`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequeryrow) | Interface | A row in a complete raw result, paired with its opaque Realtime identity. |
| [`RawLiveQuerySubscription`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequerysubscription) | Interface | A live-query subscription that exposes ordered raw result updates. |
| [`RealtimeClient`](https://neon.com/docs/realtime/sdks/typescript/client#client-realtimeclient) | Interface | A client that multiplexes independently disposable subscriptions. |
| [`RealtimeClientOptions`](https://neon.com/docs/realtime/sdks/typescript/client#client-realtimeclientoptions) | Interface | Configuration for a reusable Realtime browser client. |
| [`WebSocketLike`](https://neon.com/docs/realtime/sdks/typescript/client#client-websocketlike) | Interface | Minimal WebSocket contract used by the Realtime client. |
| [`LiveQueryChange`](https://neon.com/docs/realtime/sdks/typescript/client#client-livequerychange) | Type alias | A row upsert, removal, or sequential move in an atomic publication batch. |
| [`LiveQuerySnapshot`](https://neon.com/docs/realtime/sdks/typescript/client#client-livequerysnapshot) | Type alias | Materialized query rows paired with their atomic lifecycle state. |
| [`LiveQueryState`](https://neon.com/docs/realtime/sdks/typescript/client#client-livequerystate) | Type alias | Atomic lifecycle state for a live-query subscription. |
| [`PostgreSQLBytesParser`](https://neon.com/docs/realtime/sdks/typescript/client#client-postgresqlbytesparser) | Type alias | A parser for PostgreSQL `bytea`, transported as decoded bytes. |
| [`PostgreSQLParserForOid`](https://neon.com/docs/realtime/sdks/typescript/client#client-postgresqlparserforoid) | Type alias | Parser input selected by the fixed Realtime OID/codec mapping. |
| [`PostgreSQLParsers`](https://neon.com/docs/realtime/sdks/typescript/client#client-postgresqlparsers) | Type alias | A sparse collection of result parsers keyed by PostgreSQL type OID. |
| [`PostgreSQLTextParser`](https://neon.com/docs/realtime/sdks/typescript/client#client-postgresqltextparser) | Type alias | A parser for a PostgreSQL value transported with the `pg_text` codec. |
| [`RawLiveQueryUpdate`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequeryupdate) | Type alias | 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`](https://neon.com/docs/realtime/sdks/typescript/client#client-realtimelogentry) | Type alias | Structured client diagnostic passed to a configured logger. Narrowing on `event` also narrows the metadata available on the entry. |
| [`RealtimeLogEvent`](https://neon.com/docs/realtime/sdks/typescript/client#client-realtimelogevent) | Type alias | Stable name for one client diagnostic event. |
| [`RealtimeLogger`](https://neon.com/docs/realtime/sdks/typescript/client#client-realtimelogger) | Type alias | Receives structured Realtime client diagnostics. |
| [`RealtimeLogLevel`](https://neon.com/docs/realtime/sdks/typescript/client#client-realtimeloglevel) | Type alias | Client-side diagnostic verbosity. |
| [`WebSocketFactory`](https://neon.com/docs/realtime/sdks/typescript/client#client-websocketfactory) | Type alias | Create a WebSocket-compatible transport for the Realtime client. |
| [`nodePostgresParsers`](https://neon.com/docs/realtime/sdks/typescript/client#client-nodepostgresparsers) | Variable | 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`](https://neon.com/docs/realtime/sdks/typescript/client#client-pgtypeoids) | Variable | Stable PostgreSQL type OIDs used by the built-in Realtime parsers. |
| [`postgresJsParsers`](https://neon.com/docs/realtime/sdks/typescript/client#client-postgresjsparsers) | Variable | Parsers that differ from the core defaults when matching Postgres.js. Spread this partial preset into the client's `parsers` option. |
| [`SealedLiveQuery`](https://neon.com/docs/realtime/sdks/typescript/client#client-sealedlivequery) | Re-export | |

### createRealtimeClient

```ts
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

| Name | Type | Description |
| - | - | - |
| `options` | `RealtimeClientOptions` | Browser client configuration, including the proxy WebSocket URL. |

#### Returns

`RealtimeClient`

### defineParsers

```ts
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

| Name | Type | Description |
| - | - | - |
| `parsers` | `BuiltInParsers` | |

#### Returns

`PostgreSQLParsers`

```ts
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

| Name | Type | Description |
| - | - | - |
| `parsers` | `Readonly<Record<number, PostgreSQLTextParser>>` | |

#### Returns

`PostgreSQLParsers`

### QueryRefreshController

```ts
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

| Name | Type | Description |
| - | - | - |
| `constructor` | `new <Row>(options: QueryRefreshControllerOptions<Row>) => QueryRefreshController<Row>` | |
| `currentQuery` | `() => SealedLiveQuery<Row>` | Return the capability currently managed by this controller. |
| [`replaceSealedQuery`](https://neon.com/docs/realtime/sdks/typescript/client#client-queryrefreshcontrollerreplacesealedquery) | `(query: SealedLiveQuery<Row>) => Promise<void>` | Apply a replacement capability immediately and schedule its next refresh. |
| `setRefreshCallback` | `(refreshQuery: (() => Promise<SealedLiveQuery<Row>>) \| undefined) => void` | Replace the callback used to obtain a fresh capability. Passing `undefined` disables scheduled refreshes without stopping the controller. |
| `setSubscription` | `(subscription: RawLiveQuerySubscription<Row> \| undefined) => void` | Associate the active subscription managed by this controller. |
| `start` | `() => void` | Start scheduling refreshes. Calling this more than once has no effect. |
| `stop` | `() => void` | Stop scheduling refreshes and ignore any refresh already in flight. |

#### QueryRefreshController.replaceSealedQuery

```ts
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**

| Name | Type | Description |
| - | - | - |
| `query` | `SealedLiveQuery<Row>` | |

### LiveQueryBatchInfo

```ts
interface LiveQueryBatchInfo
```

Metadata for one atomically published batch of PostgreSQL transactions.

#### Members

| Name | Type | Description |
| - | - | - |
| `txids` | `readonly string[]` | Exact PostgreSQL transaction IDs represented as decimal strings. |

### LiveQueryError

```ts
interface LiveQueryError extends Error
```

An error reported by a live-query subscription.

#### Members

| Name | Type | Description |
| - | - | - |
| `cause?` | `unknown` | |
| `code` | `readonly string` | Stable machine-readable error code. |
| `message` | `string` | |
| `name` | `string` | |
| `retryable` | `readonly boolean` | Whether reconnecting or obtaining a fresh sealed query may recover it. |
| `sqlState?` | `readonly string` | PostgreSQL SQLSTATE supplied for an authenticated debug query failure. |
| `stack?` | `string` | |

### MaterializedLiveQueryOptions

```ts
interface MaterializedLiveQueryOptions<Row>
```

Options for the default materialized subscription.

#### Members

| Name | Type | Description |
| - | - | - |
| `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 true` | Select materialization; omitted and `true` are equivalent. |

### MaterializedLiveQuerySubscription

```ts
interface MaterializedLiveQuerySubscription<Row> extends RawLiveQuerySubscription<Row>
```

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

#### Members

| Name | Type | Description |
| - | - | - |
| [`awaitRows`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequerysubscriptionawaitrows) | `(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`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequerysubscriptionawaittxid) | `(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` | `() => LiveQueryState` | Return the complete current lifecycle state. |
| [`onChange`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequerysubscriptiononchange) | `(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. |
| [`onStateChange`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequerysubscriptiononstatechange) | `(listener: (state: LiveQueryState) => void) => () => void` | Observe lifecycle transitions. |
| [`onUpdate`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequerysubscriptiononupdate) | `(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. |
| [`renew`](https://neon.com/docs/realtime/sdks/typescript/client#client-materializedlivequerysubscriptionrenew) | `(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` | `() => void` | Permanently close this subscription and remove its listeners. |

#### MaterializedLiveQuerySubscription.awaitRows

```ts
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**

| Name | Type | Description |
| - | - | - |
| `matches` | `(rows: readonly Row[]) => boolean` | Predicate evaluated against each complete row snapshot. |
| `timeout?` | `number` | Optional maximum wait in milliseconds. By default the promise remains pending until the rows match or the subscription closes. |

#### MaterializedLiveQuerySubscription.awaitTxId

```ts
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**

| Name | Type | Description |
| - | - | - |
| `txid` | `string` | PostgreSQL transaction ID as a decimal string. |
| `timeout?` | `number` | Optional maximum wait in milliseconds. By default the promise remains pending until the transaction arrives, the subscription fails, or the subscription closes. |

#### MaterializedLiveQuerySubscription.onChange

```ts
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**

| Name | Type | Description |
| - | - | - |
| `listener` | `(snapshot: LiveQuerySnapshot<Row>) => void` | |

#### MaterializedLiveQuerySubscription.onStateChange

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

Observe lifecycle transitions.

**Returns:** A function that removes this listener.

**Parameters**

| Name | Type | Description |
| - | - | - |
| `listener` | `(state: LiveQueryState) => void` | |

#### MaterializedLiveQuerySubscription.onUpdate

```ts
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**

| Name | Type | Description |
| - | - | - |
| `listener` | `(update: RawLiveQueryUpdate<Row>) => void` | |

#### MaterializedLiveQuerySubscription.renew

```ts
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**

| Name | Type | Description |
| - | - | - |
| `query` | `SealedLiveQuery<Row>` | |

### RawLiveQueryOptions

```ts
interface RawLiveQueryOptions
```

Options for a raw, non-materializing subscription.

#### Members

| Name | Type | Description |
| - | - | - |
| `materialize` | `readonly false` | Disable SDK materialization and consume raw result updates directly. |

### RawLiveQueryRow

```ts
interface RawLiveQueryRow<Row>
```

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

#### Members

| Name | Type | Description |
| - | - | - |
| `row` | `readonly Row` | Decoded query row. |
| `rowId` | `readonly string` | Opaque identity invalidated by the next complete `rows` update. |

### RawLiveQuerySubscription

```ts
interface RawLiveQuerySubscription<Row>
```

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

#### Members

| Name | Type | Description |
| - | - | - |
| [`awaitTxId`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequerysubscriptionawaittxid) | `(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` | `() => LiveQueryState` | Return the complete current lifecycle state. |
| [`onStateChange`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequerysubscriptiononstatechange) | `(listener: (state: LiveQueryState) => void) => () => void` | Observe lifecycle transitions. |
| [`onUpdate`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequerysubscriptiononupdate) | `(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. |
| [`renew`](https://neon.com/docs/realtime/sdks/typescript/client#client-rawlivequerysubscriptionrenew) | `(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` | `() => void` | Permanently close this subscription and remove its listeners. |

#### RawLiveQuerySubscription.awaitTxId

```ts
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**

| Name | Type | Description |
| - | - | - |
| `txid` | `string` | PostgreSQL transaction ID as a decimal string. |
| `timeout?` | `number` | Optional maximum wait in milliseconds. By default the promise remains pending until the transaction arrives, the subscription fails, or the subscription closes. |

#### RawLiveQuerySubscription.onStateChange

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

Observe lifecycle transitions.

**Returns:** A function that removes this listener.

**Parameters**

| Name | Type | Description |
| - | - | - |
| `listener` | `(state: LiveQueryState) => void` | |

#### RawLiveQuerySubscription.onUpdate

```ts
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**

| Name | Type | Description |
| - | - | - |
| `listener` | `(update: RawLiveQueryUpdate<Row>) => void` | |

#### RawLiveQuerySubscription.renew

```ts
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**

| Name | Type | Description |
| - | - | - |
| `query` | `SealedLiveQuery<Row>` | |

### RealtimeClient

```ts
interface RealtimeClient
```

A client that multiplexes independently disposable subscriptions.

#### Members

| Name | Type | Description |
| - | - | - |
| `close` | `() => void` | Permanently close all subscriptions and the underlying WebSocket. |
| [`subscribe`](https://neon.com/docs/realtime/sdks/typescript/client#client-realtimeclientsubscribe) | `<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

```ts
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**

| Name | Type | Description |
| - | - | - |
| `query` | `SealedLiveQuery<Row>` | Short-lived capability returned by the application backend. |
| `options?` | `MaterializedLiveQueryOptions<NoInferCompat<Row>>` | Materialization and optional preloaded-row settings. |

```ts
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**

| Name | Type | Description |
| - | - | - |
| `query` | `SealedLiveQuery<Row>` | Short-lived capability returned by the application backend. |
| `options` | `RawLiveQueryOptions` | Set `materialize` to `false` to consume raw events. |

### RealtimeClientOptions

```ts
interface RealtimeClientOptions
```

Configuration for a reusable Realtime browser client.

#### Members

| Name | Type | Description |
| - | - | - |
| `logger?` | `readonly RealtimeLogger` | Structured 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 RealtimeLogLevel` | Minimum 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`](https://neon.com/docs/realtime/sdks/typescript/client#client-nodepostgresparsers). The client snapshots the object when it is created, so later mutations have no effect. |
| `url` | `readonly string` | Realtime proxy WebSocket URL, using `wss:` outside local development. |
| `webSocketFactory?` | `readonly WebSocketFactory` | Override 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

```ts
interface WebSocketLike
```

Minimal WebSocket contract used by the Realtime client.

#### Members

| Name | Type | Description |
| - | - | - |
| `readyState` | `readonly 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?` | `() => void` | Immediately destroy the transport when the implementation supports it. |

### LiveQueryChange

```ts
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

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

Materialized query rows paired with their atomic lifecycle state.

### LiveQueryState

```ts
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

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

A parser for PostgreSQL `bytea`, transported as decoded bytes.

### PostgreSQLParserForOid

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

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

### PostgreSQLParsers

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

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

### PostgreSQLTextParser

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

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

### RawLiveQueryUpdate

```ts
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

```ts
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

```ts
type RealtimeLogEvent = keyof RealtimeLogEventDefinition
```

Stable name for one client diagnostic event.

### RealtimeLogger

```ts
type RealtimeLogger = (entry: RealtimeLogEntry) => void
```

Receives structured Realtime client diagnostics.

### RealtimeLogLevel

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

Client-side diagnostic verbosity.

### WebSocketFactory

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

Create a WebSocket-compatible transport for the Realtime client.

### nodePostgresParsers

```ts
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

```ts
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

```ts
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](https://neon.com/docs/realtime/sdks/typescript/backend#backend-sealedlivequery).

---

## Related docs (TypeScript)

- [Backend](https://neon.com/docs/realtime/sdks/typescript/backend)
- [React](https://neon.com/docs/realtime/sdks/typescript/react)
- [TanStack DB](https://neon.com/docs/realtime/sdks/typescript/tanstack-db)
- [Drizzle](https://neon.com/docs/realtime/sdks/typescript/drizzle)
- [Kysely](https://neon.com/docs/realtime/sdks/typescript/kysely)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/docs/realtime/sdks/typescript/client"}` to https://feedback.neon.tech/ (no auth required).
