Security News
Bun 1.2 Released with 90% Node.js Compatibility and Built-in S3 Object Support
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
@supabase/realtime-js
Advanced tools
@supabase/realtime-js is a JavaScript client for interacting with Supabase's real-time features. It allows developers to subscribe to changes in their database and receive updates in real-time, enabling functionalities such as live data synchronization, real-time notifications, and collaborative applications.
Real-time Database Changes
This feature allows you to subscribe to changes in a specific table in your Supabase database. The code sample demonstrates how to set up a subscription to listen for any changes (insert, update, delete) on the 'your_table' table and log the payload of the change.
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient('https://your-project.supabase.co', 'public-anon-key');
const subscription = supabase
.from('your_table')
.on('*', payload => {
console.log('Change received!', payload);
})
.subscribe();
Real-time Insertions
This feature allows you to subscribe specifically to insertions in a table. The code sample shows how to listen for new rows being added to 'your_table' and log the payload of the new row.
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient('https://your-project.supabase.co', 'public-anon-key');
const subscription = supabase
.from('your_table')
.on('INSERT', payload => {
console.log('New row added!', payload);
})
.subscribe();
Real-time Updates
This feature allows you to subscribe specifically to updates in a table. The code sample demonstrates how to listen for updates to rows in 'your_table' and log the payload of the updated row.
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient('https://your-project.supabase.co', 'public-anon-key');
const subscription = supabase
.from('your_table')
.on('UPDATE', payload => {
console.log('Row updated!', payload);
})
.subscribe();
Real-time Deletions
This feature allows you to subscribe specifically to deletions in a table. The code sample shows how to listen for rows being deleted from 'your_table' and log the payload of the deleted row.
const { createClient } = require('@supabase/supabase-js');
const supabase = createClient('https://your-project.supabase.co', 'public-anon-key');
const subscription = supabase
.from('your_table')
.on('DELETE', payload => {
console.log('Row deleted!', payload);
})
.subscribe();
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.
Listens to changes in a PostgreSQL Database and via websockets.
This is for usage with Supabase Realtime server.
You can set up one connection to be used across the whole app.
import { RealtimeClient } from '@supabase/realtime-js'
var client = new RealtimeClient(process.env.REALTIME_URL)
client.connect()
REALTIME_URL is 'ws://localhost:4000/socket'
when developing locally and 'wss://<project_ref>.supabase.co/realtime/v1'
when connecting to your Supabase project.
You can pass in your JWT If you have enabled JWT authorization in Supabase Realtime server.
import { RealtimeClient } from '@supabase/realtime-js'
var client = new RealtimeClient(process.env.REALTIME_URL, { params: { apikey: 'token123' }})
client.connect()
See Realtime: Websocket Connection Authorization for more information.
Socket Hooks
client.onOpen(() => console.log('Socket opened.'))
client.onClose(() => console.log('Socket closed.'))
client.onError((e) => console.log('Socket error', e.message))
You can listen to INSERT
, UPDATE
, DELETE
, or all *
events.
You can subscribe to events on the whole database, schema, table, or individual columns using channel()
. Channels are multiplexed over the Socket connection.
To join a channel, you must provide the topic
, where a topic is either:
realtime
- entire databaserealtime:{schema}
- where {schema}
is the Postgres Schemarealtime:{schema}:{table}
- where {table}
is the Postgres table namerealtime:{schema}:{table}:{col}=eq.{val}
- where {col}
is the column name, and {val}
is the value which you want to matchExamples
// Listen to events on the entire database.
var databaseChanges = client.channel('realtime:*')
databaseChanges.on('*', (e) => console.log(e))
databaseChanges.on('INSERT', (e) => console.log(e))
databaseChanges.on('UPDATE', (e) => console.log(e))
databaseChanges.on('DELETE', (e) => console.log(e))
databaseChanges.subscribe()
// Listen to events on a schema, using the format `realtime:{SCHEMA}`
var publicSchema = client.channel('realtime:public')
publicSchema.on('*', (e) => console.log(e))
publicSchema.on('INSERT', (e) => console.log(e))
publicSchema.on('UPDATE', (e) => console.log(e))
publicSchema.on('DELETE', (e) => console.log(e))
publicSchema.subscribe()
// Listen to events on a table, using the format `realtime:{SCHEMA}:{TABLE}`
var usersTable = client.channel('realtime:public:users')
usersTable.on('*', (e) => console.log(e))
usersTable.on('INSERT', (e) => console.log(e))
usersTable.on('UPDATE', (e) => console.log(e))
usersTable.on('DELETE', (e) => console.log(e))
usersTable.subscribe()
// Listen to events on a row, using the format `realtime:{SCHEMA}:{TABLE}:{COL}=eq.{VAL}`
var rowChanges = client.channel('realtime:public:users:id=eq.1')
rowChanges.on('*', (e) => console.log(e))
rowChanges.on('INSERT', (e) => console.log(e))
rowChanges.on('UPDATE', (e) => console.log(e))
rowChanges.on('DELETE', (e) => console.log(e))
rowChanges.subscribe()
Removing a subscription
You can unsubscribe from a topic using channel.unsubscribe()
.
Disconnect the socket
Call disconnect()
on the socket:
let { error, data } = await client.disconnect()
Duplicate Join Subscriptions
While the client may join any number of topics on any number of channels, the client may only hold a single subscription for each unique topic at any given time. When attempting to create a duplicate subscription, the server will close the existing channel, log a warning, and spawn a new channel for the topic. The client will have their channel.onClose
callbacks fired for the existing channel, and the new
channel join will have its receive hooks processed as normal.
Channel Hooks
channel.onError( () => console.log("there was an error!") )
channel.onClose( () => console.log("the channel has gone away gracefully") )
onError
hooks are invoked if the socket connection drops, or the channel crashes on the server. In either case, a channel rejoin is attempted automatically in an exponential backoff manner.onClose
hooks are invoked only in two cases. 1) the channel explicitly closed on the server, or 2). The client explicitly closed, by calling channel.unsubscribe()
Subscription Hooks
publicSchema
.subscribe()
.receive('ok', () => console.log('Connected.'))
.receive('error', () => console.log('Failed.'))
.receive('timeout', () => console.log('Timed out, retrying.'))
Events are returned in the following format.
type Response = {
// the change timestamp. eg: "2020-10-13T10:09:22Z".
commit_timestamp: string
// the database schema. eg: "public".
schema: string
// the database table. eg: "users".
table: string
// the event type.
type: INSERT | UPDATE | DELETE
// all the columns for this table. See "column" type below.
columns: column[]
// the new values. eg: { "id": "9", "age": "12" }.
record: object
// the previous values. eg: { "id": "9", "age": "11" }. Only works if the table has `REPLICATION FULL`.
old_record: object
// any change errors.
errors: null | string[]
}
type column = {
// any special flags for the column. eg: ["key"]
flags: string[]
// the column name. eg: "user_id"
name: string
// the column type. eg: "uuid"
type: string
// the type modifier. eg: 4294967295
type_modifier: number
}
MIT. License is the same as phoenix-channels and Phoenix Framework.
FAQs
Listen to realtime updates to your PostgreSQL database
The npm package @supabase/realtime-js receives a total of 705,737 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 12 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.
Security News
Fluent Assertions is facing backlash after dropping the Apache license for a commercial model, leaving users blindsided and questioning contributor rights.