This page shows how to build a Realtime app with Drizzle ORM, using your existing schema, queries, types and writes. You'll learn which Drizzle queries seal unchanged, when a field needs an SQL alias, how live rows keep Drizzle's types in the browser, and how a Drizzle write returns its transaction ID.
Full examples on GitHub
These apps in the neondatabase/examples repository use Drizzle:
realtime/guides-chat-app: the chat app the guides build, with a snake_case schemarealtime/with-react: Hono and React, with a minimal Drizzle setuprealtime/with-tanstack: TanStack Start, with a camelCase schema and an aliased columnrealtime/with-nextjs: Next.js and Managed Better Auth, with a per-user snake_case schema
Setup
Install the packages
Install the Realtime SDK, its Drizzle adapter, Drizzle and a Postgres driver:
npm install @neon/realtime @neon/realtime-drizzle drizzle-orm pg
npm install -D @types/pg@neon/realtime-drizzle has two entry points. The main one exports drizzleAdapter() for your server. @neon/realtime-drizzle/client exports drizzleParsers for the browser and doesn't import Drizzle, so the ORM stays out of your browser bundle.
The queries guide's setup covers the rest: Neon's Managed Better Auth, neon.ts and the environment variables. For Drizzle on Neon in general, see Connect from Drizzle to Neon.
Create the Realtime server
Pass drizzleAdapter() to createRealtime, so the Realtime server accepts Drizzle queries:
import { createRealtime } from "@neon/realtime/server"
import { drizzleAdapter } from "@neon/realtime-drizzle"
export const realtime = createRealtime({
secret: process.env.NEON_REALTIME_SECRET!,
db: "neondb",
adapter: drizzleAdapter()
})drizzleAdapter()takes no options. When you seal a Drizzle select, it compiles it to SQL and bind parametersdbis the database name, such as"neondb", not a Drizzle client. Use the database in yourDATABASE_URL, and keepNEON_REALTIME_SECRETon the server- the same server still seals
rawSqlqueries, so you can mix the two. Addurland it can subscribe in trusted backend code, wheresubscribe()takes a Drizzle query directly
Defining queries
Define live queries with your usual Drizzle schema, client and select builder, in server code.
Define the schema
Your schema stays plain Drizzle, with no Realtime imports or options. The choice that matters is how you name the keys. Snake_case keys, the same as the column names, are the simplest:
import { integer, pgTable, primaryKey, text, timestamp, uuid } from "drizzle-orm/pg-core"
export const messages = pgTable("messages", {
// No default: the client generates the ID, so an optimistic row already has its key
id: uuid("id").primaryKey(),
channel_id: integer("channel_id").notNull(),
author_id: text("author_id").notNull(),
body: text("body").notNull(),
created_at: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
})
export const channelMembers = pgTable(
"channel_members",
{
channel_id: integer("channel_id").notNull(),
user_id: text("user_id").notNull()
},
(table) => [primaryKey({ columns: [table.channel_id, table.user_id] })]
)
export type Message = typeof messages.$inferSelect- the adapter needs every selected key to match the name Postgres returns for it. With snake_case keys, no query needs an alias. For camelCase keys, see Alias renamed and computed fields
- give each table a primary key. That's all Realtime needs from it. See the table requirements
Messageis the row type of a select of everymessagescolumn. You'll use it when you type rows in the browser
Create the tables with your usual Drizzle workflow. Realtime needs nothing extra from your migrations: no publications, triggers or grants. See Schema migration with Neon Postgres and Drizzle ORM.
Create the Drizzle client
You build live queries with your usual Drizzle db, but Realtime never runs them through it: the adapter only compiles them to SQL. db still runs your writes and any reads on the server, such as server-rendered rows:
import { drizzle } from "drizzle-orm/node-postgres"
import { Pool } from "pg"
import * as schema from "./schema"
const pool = new Pool({
// Neon URLs say sslmode=require. Asking pg for verify-full keeps today's checks and skips its warning
connectionString: process.env.DATABASE_URL!.replace("sslmode=require", "sslmode=verify-full")
})
export const db = drizzle(pool, { schema })
// So an idle connection error, for example when the compute scales to zero, doesn't crash the API
pool.on("error", (error: Error) => console.error(error))- any Drizzle Postgres driver works,
neon-httpincluded, because each write returns its transaction ID in one statement. This page usesdrizzle-orm/node-postgreswith apgpool { schema }is only for Drizzle's relationaldb.queryAPI, which can't be sealed. Live queries use the select builder
Define the live query
A live query is a Drizzle select that you build but don't await. Wrap it in a function, so each call builds a fresh query for its values:
import { and, desc, eq, getTableColumns } from "drizzle-orm"
import { db } from "./db"
import { channelMembers, messages } from "./schema"
export function messagesQuery(userId: string, channelId: number) {
return db
.select(getTableColumns(messages))
.from(messages)
.innerJoin(channelMembers, eq(channelMembers.channel_id, messages.channel_id))
.where(and(eq(channelMembers.user_id, userId), eq(messages.channel_id, channelId)))
.orderBy(desc(messages.created_at))
.limit(50)
}select(getTableColumns(messages))keeps each row flat, with only themessagescolumns. A bareselect()over a join doesn't seal- the join is the authorization: a user only sees messages in channels they belong to, even as memberships change. See live authorization
orderByandlimitwork as in any Drizzle query, so the live result is the 50 newest messages- await the same function to read the rows on the server, for example to server-render the first results. See return the sealed query and initial results
The adapter checks the query's shape when you seal it. The SQL is only checked when a client subscribes, so a query that writes or calls a non-deterministic function such as now() seals and then fails to subscribe. See the rules for defining live queries.
Alias renamed and computed fields
Realtime returns rows with the names Postgres gives each result column, not the keys Drizzle maps them to. So seal() throws if a selected key doesn't match its result name. Snake_case keys always match. With camelCase keys over snake_case columns, a renamed field needs an SQL alias. Here's messages with camelCase keys:
import { integer, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"
export const messages = pgTable("messages", {
id: uuid("id").primaryKey(),
channelId: integer("channel_id").notNull(),
authorId: text("author_id").notNull(),
body: text("body").notNull(),
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow()
})A query over it aliases createdAt, the one selected key that differs from its column:
import { eq, sql } from "drizzle-orm"
import { db } from "./db"
import { messages } from "./schema"
export function userMessagesQuery(userId: string) {
return db
.select({
id: messages.id,
body: messages.body,
createdAt: sql<Date>`${messages.createdAt}`.mapWith(messages.createdAt).as("createdAt")
})
.from(messages)
.where(eq(messages.authorId, userId))
}idandbodymatch their columns, so they need nothing- on its own,
createdAt: messages.createdAtcomes back ascreated_at, andseal()throws.sql<Date>`${messages.createdAt}`.as("createdAt")selects"created_at" as "createdAt", andsql<Date>keeps the row type aDate .mapWith(messages.createdAt)only matters when Drizzle runs the query, for example when you await it to server-render. It decodes with the column's decoder, so you get aDatethere too. Live rows don't need it: the Realtime client decodes by Postgres type. See keep row shapes identical- only selected keys need to match, so filtering on
authorIdneeds no alias
Computed fields, such as aggregates, follow the same rule: alias each one to its key, as in messageCount: sql<number>`count(*)::int`.as("messageCount"). Cast with ::int because Postgres returns count(*) as int8, which arrives as a string.
Sealing queries
Seal each query on the server. The browser can subscribe to a sealed query, but it can't read or change it, as the queries guide explains in sealing queries.
Pass query parameters
Drizzle has no special syntax for live query parameters: they're the values you pass to the query function. Fill them in on the server from context you trust. Take the user ID from the verified session, validate anything from the request, then seal with realtime.seal({ query: messagesQuery(user.id, channelId) }). The queries guide shows this in an API endpoint and a server function.
- Drizzle compiles each value to a bind parameter. The sealed query carries the values alongside the SQL, never spliced into it
- each sealed query is for one set of values. To show another channel, the browser fetches a new sealed query. See changing query parameters and renewing sealed queries
Parameter types
Values you compare with a column go through that column's Drizzle encoder. So unlike raw SQL parameters, a Date or JSON value needs no pgParam wrapper. This Drizzle version of the queries guide's messagesSinceQuery passes since straight to gt():
import { and, desc, eq, getTableColumns, gt } from "drizzle-orm"
import { db } from "./db"
import { channelMembers, messages } from "./schema"
export function messagesSinceQuery(userId: string, channelId: number, since: Date) {
return db
.select(getTableColumns(messages))
.from(messages)
.innerJoin(channelMembers, eq(channelMembers.channel_id, messages.channel_id))
.where(
and(
eq(channelMembers.user_id, userId),
eq(messages.channel_id, channelId),
gt(messages.created_at, since)
)
)
.orderBy(desc(messages.created_at))
.limit(50)
}The timestamptz column encodes since as an ISO string, and Postgres infers the parameter's type from the SQL.
Subscribing to queries
Subscribe in the browser as the subscribing guide shows. @neon/realtime-drizzle/client adds parsers that decode live rows like Drizzle results, and seal() gives the rows their type.
Decode rows withdrizzleParsers
Spread drizzleParsers into the Realtime client's parsers, so live rows decode the way Drizzle decodes the same columns:
import { createRealtimeClient } from "@neon/realtime/client"
import { drizzleParsers } from "@neon/realtime-drizzle/client"
export const client = createRealtimeClient({
url: import.meta.env.VITE_NEON_REALTIME_URL,
parsers: { ...drizzleParsers }
})The parsers work by Postgres type, so for common column types a live row matches Drizzle's type. The exception is bigint, in either mode, which arrives as a string:
| Drizzle column | Drizzle's type | Live value with drizzleParsers |
|---|---|---|
timestamp({ withTimezone: true }) | Date | Date |
timestamp() | Date | Date, read as UTC |
date() | string | string |
integer() | number | number |
boolean() | boolean | boolean |
jsonb() | unknown | the parsed JSON value |
numeric() | string | string |
bigint({ mode: "number" }) | number | string |
bigint({ mode: "bigint" }) | bigint | string |
Per-column modes, such as date({ mode: "date" }) or timestamp({ mode: "string" }), aren't carried over. Nor are custom types or columns that Drizzle maps to tuples or arrays, such as point(), line() and vector(). For those, and for bigint, register a parser for the Postgres type with defineParsers, and decode server-rendered rows the same way. The subscribing guide lists every default parser.
Type rows in the browser
You don't write the row type yourself. seal() infers it from the select: realtime.seal({ query: messagesQuery(userId, channelId) }) returns a SealedLiveQuery<Message>. A typed API client, such as Hono's hc, carries that type to the browser. Hono types the response as JSON, though, so it types a Date column such as created_at as a string, while live rows decode it to a Date. See fetch from an API endpoint.
- to name the row type in the browser, use
import type { Message } from "../backend/schema". TypeScript erases the import, so the schema stays out of the browser bundle $inferSelectfitsmessagesQuerybecause it selects every column. For a narrower or aliased selection, derive the type from the query:type UserMessage = Awaited<ReturnType<typeof userMessagesQuery>>[number]- for the rest, see subscribing to the sealed query and the React and TanStack DB bindings
Optimistic mutations
The client holds each optimistic change until the write's transaction ID comes back on the subscription, so every write returns its txid. The mutations guide explains how optimistic mutations work.
Return the txid from Drizzle writes
Return the transaction ID from the write itself, by adding pg_current_xact_id() to its RETURNING. For example, a function that edits a message:
import { and, eq, ne, sql } from "drizzle-orm"
import { db } from "./db"
import { messages } from "./schema"
export type MutationResponse =
| { readonly kind: "committed"; readonly txid: string }
| { readonly kind: "unchanged" }
// The id of the transaction that made the change, read in the write's own RETURNING
const txid = sql<string>`pg_current_xact_id()::text`
const mutationResponse = (row?: { txid: string }): MutationResponse =>
row ? { kind: "committed", txid: row.txid } : { kind: "unchanged" }
export async function editMessage(userId: string, id: string, body: string): Promise<MutationResponse> {
const [row] = await db
.update(messages)
.set({ body })
.where(and(eq(messages.id, id), eq(messages.author_id, userId), ne(messages.body, body)))
.returning({ txid })
return mutationResponse(row)
}- a single statement runs in its own transaction, so
RETURNINGgives you the ID of the transaction that made the change, in one round trip. Don't wrap the write indb.transaction()just to read the ID: that adds three more round trips and holds a connection - the
textcast keeps the 64-bit ID exact, as the decimal string the client waits for - with no changed row, nothing comes over Realtime, so
mutationResponse()returnsunchangedand the client has nothing to wait for.ne(messages.body, body)skips edits that change nothing - see how to call these writes from the frontend
Common pitfalls
These Drizzle query shapes don't work as live queries. All but the last fail on the server: TypeScript rejects .prepare(), and the rest make seal() throw:
- a bare
select()over a join. Drizzle nests each row by table, and the adapter can't name the nested fields. Select a flat object, such asgetTableColumns(messages)or{ id: messages.id, body: messages.body }. A column from another table under a different key needs a matching alias - renamed keys and unaliased computed fields.
{ authorId: messages.author_id }and{ total: count() }throw until you add an SQL alias - relational queries, prepared statements and placeholders.
db.query.messages.findMany(),.prepare()andsql.placeholder()don't give a select builder with bound values. Build a new select for each set of values, as the query functions do - a
Dateor object straight inside asqltemplate.sql`${messages.created_at} > ${since}`throws, because no column encodessince. Use a column operator such asgt(messages.created_at, since), or passsince.toISOString() - Drizzle's
casing: "snake_case"option. With camelCase keys that don't name their columns, Drizzle writescreated_atinto the SQL, but the adapter checks the Drizzle name,createdAt. The query seals, and live rows havecreated_atwhile the type sayscreatedAt. Name each column, as intimestamp("created_at"), and alias the renamed keys
Next steps
- read the queries guide
- see how the client applies writes optimistically in the mutations guide
- look up
drizzleAdapter()anddrizzleParsersin the Drizzle section of the SDK reference - see Drizzle in a full-stack app in the Next.js and TanStack examples
- browse the full source of the chat app,
with-react,with-tanstackandwith-nextjson GitHub
Need help?
Join our Discord Server to ask questions or see what others are doing with Neon. For paid plan support options, see Support.








