Send ephemeral messages with Broadcast, track and synchronize state with Presence, and listen to database changes with Postgres Change Data Capture (CDC).
This SDK enables you to use the following Supabase Realtime's features:
Broadcast: send ephemeral messages from client to clients with minimal latency. Use cases include sharing cursor positions between users.
Presence: track and synchronize shared state across clients with the help of CRDTs. Use cases include tracking which users are currently viewing a specific webpage.
Postgres Change Data Capture (CDC): listen for changes in your PostgreSQL database and send them to clients.
Usage
Installing the Package
npm install @supabase/realtime-js
Creating a Channel
import { RealtimeClient } from'@supabase/realtime-js'const client = newRealtimeClient(REALTIME_URL, {
params: {
apikey: API_KEY,
},
})
const channel = client.channel('test-channel', {})
channel.subscribe((status, err) => {
if (status === 'SUBSCRIBED') {
console.log('Connected!')
}
if (status === 'CHANNEL_ERROR') {
console.log(`There was an error subscribing to channel: ${err.message}`)
}
if (status === 'TIMED_OUT') {
console.log('Realtime server did not respond in time.')
}
if (status === 'CLOSED') {
console.log('Realtime channel was unexpectedly closed.')
}
})
Notes:
REALTIME_URL is 'ws://localhost:4000/socket' when developing locally and 'wss://<project_ref>.supabase.co/realtime/v1' when connecting to your Supabase project.
API_KEY is a JWT whose claims must contain exp and role (existing database role).
Channel name can be any string.
Setting private to true means that the client will use RLS to determine if the user can connect or not to a given channel.
Broadcast
Your client can send and receive messages based on the event.
Setting ack to true means that the channel.send promise will resolve once server replies with acknowledgment that it received the broadcast message request.
Setting self to true means that the client will receive the broadcast message it sent out.
Broadcast Replay
Broadcast Replay enables private channels to access messages that were sent earlier. Only messages published via Broadcast From the Database are available for replay.
You can configure replay with the following options:
since (Required): The epoch timestamp in milliseconds, specifying the earliest point from which messages should be retrieved.
limit (Optional): The number of messages to return. This must be a positive integer, with a maximum value of 25.
config.presence.enabled (set automatically if you add an .on('presence', ...) listener)
controls whether this client receives presence state and updates from other clients —
without it, presenceState() stays empty for you. It does not affect whether other clients
see you: calling track() always makes you visible to subscribers that do have presence
enabled. On RLS-protected channels, receiving presence updates additionally requires the
presence.read policy to authorize this client.
The filter option accepts either a raw string or a
postgresChangesFilter() builder — both produce the exact same wire format, so
you can mix and match and existing string filters keep working unchanged:
// Raw string — always supported, fully backward compatible
{ event: 'UPDATE', schema: 'public', table: 'users', filter: 'id=eq.1' }
// Builder — type-checked, ergonomic; the SDK serializes it for you
{ event: 'UPDATE', schema: 'public', table: 'users', filter: postgresChangesFilter().eq('id', 1) }
A filter is a column=operator.value expression evaluated server-side. The
following operators are supported:
Operator
String form
Builder
Meaning
eq
id=eq.1
.eq('id', 1)
equal
neq
id=neq.1
.neq('id', 1)
not equal
ltltegtgte
age=gte.18
.gte('age', 18)
comparison
in
status=in.(active,pending)
.in('status', ['active', 'pending'])
in list
likeilike
title=like.%foo%
.like('title', '%foo%')
pattern match (case in/sensitive)
is
deleted_at=is.null
.is('deleted_at', null)
IS null/true/false/unknown
matchimatch
title=match.^foo
.match('title', '^foo')
POSIX regex match (~ / ~*)
isdistinct
value=isdistinct.1
.isDistinct('value', 1)
NULL-safe inequality
Negation — prefix any operator with not. (string) or use
.not(column, operator, value) (builder):
The builder (modeled on the postgrest-js filter methods) is the recommended,
type-checked way to compose filters — but it is entirely optional; raw strings
remain fully supported.
The builder exposes eq, neq, gt, gte, lt, lte, in, like,
ilike, match, imatch, is, isDistinct and not. Call .build() if you
need the raw string yourself (e.g. to log it or store it).
Values are sent verbatim — the server has no quoting/escaping, so spaces and
quotes are preserved as-is. The server separates conditions by commas outside
parentheses, so a literal comma in a scalar value can't be expressed (commas
inside in.(…) are fine); the builder throws on such values rather than
silently producing a broken filter.
Note for PostgREST users: Realtime evaluates filters server-side over a
single table's WAL — there is no resource embedding (!inner, embedded
filters) and no or() grouping. Use % (not *) for like/ilike
wildcards, since filters travel in the WebSocket payload rather than a URL.
Selecting columns
Use select to receive only a subset of columns instead of the full row. This
reduces payload size (helpful for large bytea/jsonb columns). The selected
columns must be selectable by the subscribing role:
# Complete build (from monorepo root)
pnpm nx build realtime-js
# Build with watch mode for development
pnpm nx build realtime-js --watch
# Individual build targets
pnpm nx build:main realtime-js # CommonJS build (dist/main/)
pnpm nx build:module realtime-js # ES Modules build (dist/module/)# Other useful commands
pnpm nx clean realtime-js # Clean build artifacts
pnpm nx lint realtime-js # Run ESLint
pnpm nx typecheck realtime-js # TypeScript type checking
Build Outputs
CommonJS (dist/main/) - For Node.js environments
ES Modules (dist/module/) - For modern bundlers (Webpack, Vite, Rollup)
TypeScript definitions (dist/module/index.d.ts) - Type definitions for TypeScript projects
Note: Unlike some other packages, realtime-js doesn't include a UMD build since it's primarily used in Node.js or bundled applications.
Validating Package Exports
# Check if package exports are correctly configured
pnpm nx check-exports realtime-js
This command uses "Are the types wrong?" to verify that the package exports work correctly in different environments. Run this before publishing to ensure your package can be imported correctly by all consumers.
Testing
No Docker or Supabase instance required! The realtime-js tests use mocked WebSocket connections, so they're completely self-contained.
# Run unit tests (from monorepo root)
pnpm nx test realtime-js
# Run tests with coverage report
pnpm nx test:coverage realtime-js
# Run tests in watch mode during development
pnpm nx test:watch realtime-js
Test Scripts Explained
test - Runs all unit tests once using Vitest
test:coverage - Runs tests and generates coverage report with terminal output
test:watch - Runs tests in interactive watch mode for development
The tests mock WebSocket connections using mock-socket, so you can run them anytime without any external dependencies.
Contributing
We welcome contributions! Please see our Contributing Guide for details on how to get started.
For major changes or if you're unsure about something, please open an issue first to discuss your proposed changes.
Socket.IO is a library that enables real-time, bidirectional and event-based communication between web clients and servers. Unlike @supabase/realtime-js, which is tightly integrated with Supabase's database, Socket.IO is more general-purpose and can be used for a wide range of real-time applications, including chat applications, live updates, and collaborative tools.
Pusher is a hosted service that makes it easy to add real-time data and functionality to web and mobile applications. Pusher channels provide a way to subscribe to events and receive updates in real-time. Compared to @supabase/realtime-js, Pusher is a more mature and feature-rich platform but requires a separate service subscription.
Firebase is a comprehensive app development platform that includes real-time database capabilities. Firebase Realtime Database allows you to store and sync data between your users in real-time. While @supabase/realtime-js focuses on real-time features for Supabase's PostgreSQL database, Firebase offers a NoSQL database with built-in real-time synchronization.
Listen to realtime updates to your PostgreSQL database
The npm package @supabase/realtime-js receives a total of 17,270,710 weekly downloads. As such, @supabase/realtime-js popularity was classified as popular.
We found that @supabase/realtime-js demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.It has 2 open source maintainers collaborating on the project.