The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
docs: improve and consolidate Realtime guide
Wen Bo Xie6551cc737e14
diff --git a/apps/reference/docs/about.mdx b/apps/reference/docs/about.mdxindex 41cf64120b3..f254130c552 100755--- a/apps/reference/docs/about.mdx+++ b/apps/reference/docs/about.mdx@@ -116,7 +116,7 @@ You can use it completely, or just the features you need.class="card"to={useBaseUrl('/guides/realtime')}title={'Realtime'}- description={'Build with Broadcast, Presence, and Postgres Changes.'}+ description={'Build with Broadcast, Presence, and Postgres CDC.'}style={{ height: '100%' }}/></div>diff --git a/apps/reference/docs/architecture.mdx b/apps/reference/docs/architecture.mdxindex cbf6530b138..33ac9feb6c1 100755--- a/apps/reference/docs/architecture.mdx+++ b/apps/reference/docs/architecture.mdx@@ -23,9 +23,9 @@ Most notably, we use Postgres rather than a NoSQL store. This choice was deliber| Database | Postgres | GA | [Link](/docs/guides/database) || Database | Webhooks | Alpha | || Database | Point in time Recovery | Alpha | |-| Realtime | Postgres Changes | Beta | [Link](/docs/guides/realtime/postgres-changes) |-| Realtime | Broadcast | Alpha | [Link](/docs/guides/realtime/broadcast) |-| Realtime | Presence | Alpha | [Link](/docs/guides/realtime/presence) |+| Realtime | Postgres CDC | Beta | [Link](/docs/guides/realtime/postgres-cdc) |+| Realtime | Broadcast | Alpha | [Link](/docs/guides/realtime#broadcast) |+| Realtime | Presence | Alpha | [Link](/docs/guides/realtime#presence) || Storage | | Beta | [Link](/docs/guides/storage) || Storage | CDN | Beta | [Link](/docs/guides/storage-cdn) || Edge Functions | | Beta | [Link](/docs/guides/functions) |diff --git a/apps/reference/docs/guides/realtime.mdx b/apps/reference/docs/guides/realtime.mdxindex 56442643bf5..12cc7c97fac 100644--- a/apps/reference/docs/guides/realtime.mdx+++ b/apps/reference/docs/guides/realtime.mdx@@ -1,44 +1,51 @@---id: realtimetitle: Realtime-description: Using Supabase Realtime for multiplayer functionality.+description: Supabase Realtime with Broadcast, Presence, and Postgres CDC.sidebar_label: Overview----Supabase provides a Realtime API using [Realtime](https://github.com/supabase/realtime).+Supabase provides a globally distributed cluster of [Realtime](https://github.com/supabase/realtime) servers that enable the following functionality:-You can use this to:+- [Broadcast](#broadcast): Send ephemeral messages from client to clients with low latency.+- [Presence](#presence): Track and synchrononize shared state between clients.+- [Postgres CDC](#postgres-cdc): Listen to Postgres database changes and send them to authorized clients.-- broadcast messages between users-- manage shared state between users-- listen to database changes over websockets+A [channel](https://hexdocs.pm/phoenix/channels.html) is the basic building block of Realtime and narrows the scope of data flow to subscribed clients. You can think of a channel as a chatroom where participants are able to see who's online and send and receive messages; similar to a Discord or Slack channel.-## Realtime Channels+All clients can connect to a channel and take advantage of the built-in features, Broadcast and Presence, while extenstions, like Postgres CDC, must be enabled prior to use.-In Realtime, everything is a [_channel_](https://hexdocs.pm/phoenix/channels.html).-Channels are like chatrooms where participants can join and leave—similar to Slack or Discord channels.+## Broadcast-### Broadcast+Broadcast follows the [publish-subscribe pattern](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern) where a client publishes messages to a channel with a unique identifier. For example, a user could send a message to a channel with id `room-1`.-Broadcast follows the classic Publisher/Subscriber pattern. A client (publisher) “broadcasts” messages using a unique identifier. For example, a user could send a message to a `#random` channel.+Other clients can elect to receive the message in real-time by subscribing to the channel with id `room-1`. If these clients are online and subscribed then they will receive the message.-Other clients (subscribers) can “listen” to these messages in real-time, using the unique identifier. If they are listening to the `#random` channel, then they will receive the message.+Broadcast works by connecting your client to the nearest Realtime server, which will communicate with other servers to relay messages to other clients.-A common use-case for Broadcast is sharing a user's cursor position with other clients in an online game.+A common use-case is sharing a user's cursor position with other clients in an online game.-### Presence+## Presence-Presence synchronizes shared state between users.-Presence is very similar to Broadcast, except that the state is “persisted” in the Channel-so that new joiners immediately receive the state without waiting for another user to broadcast it.-In our Slack example, when you turn on Slack you can see who's online without each individual user-sending an “I'm online” message to the new-joiner. Presence utilizes Broadcast as the transport layer.+Presence utilizes an in-memory conflict-free replicated data type (CRDT) to track and synchronize shared state in an eventually consistent manner. It computes the difference between existing state and new state changes and sends the necessary updates to clients via Broadcast.-The neat thing about Presence is that if a user is suddenly disconnected (for example, they go offline), their state will be automatically removed from the shared state.-If you've ever tried to build an “I'm online” feature which handles unexpected disconnects, you'll appreciate how useful this is.+When a new client subscribes to a channel, it will immediately receive the channel's latest state in a single message instead of waiting for all other clients to send their individual states.-### Database changes+Clients are free to come-and-go as they please, and as long as they are all subscribed to the same channel then they will all have the same Presence state as each other.-You can subscribe to database changes using Realtime.-The Realtime API works through PostgreSQL's replication functionality. Postgres sends database changes to a [publication](/docs/guides/database/replication#publications)-called `supabase_realtime`, and by managing this publication you can control which data is broadcast.+The neat thing about Presence is that if a client is suddenly disconnected (for example, they go offline), their state will be automatically removed from the shared state. If you've ever tried to build an “I'm online” feature which handles unexpected disconnects, you'll appreciate how useful this is.++## Postgres CDC++Postgres Change Data Capture (CDC) enables you to listen to database changes and have them broadcast to authorized clients based on [Row Level Security (RLS)](/docs/guides/auth/row-level-security) policies.++This works by Realtime polling your database's logical replication slot for changes, passing those changes to the [apply_rls](https://github.com/supabase/walrus#reading-wal) SQL function to determine which clients have permission, and then using Broadcast to send those changes to clients.++Realtime requires a publication called `supabase_realtime` to determine which tables to poll. You must add tables to this publication prior to clients subscribing to channels that want to listen for database changes.++We strongly encourage you to enable RLS on your database tables and have RLS policies in place to prevent unauthorized parties from accessing your data.++## See Also++- [Realtime quickstart](/docs/guides/realtime/quickstart)+- [Realtime: Multiplayer Edition](https://supabase.com/blog/supabase-realtime-multiplayer-general-availability) blog postdiff --git a/apps/reference/docs/guides/realtime/broadcast.mdx b/apps/reference/docs/guides/realtime/broadcast.mdxdeleted file mode 100644index 15ae31f1977..00000000000--- a/apps/reference/docs/guides/realtime/broadcast.mdx+++ /dev/null@@ -1,70 +0,0 @@-----id: broadcast-title: Broadcast-description: Getting started with Realtime's Broadcast feature------Supabase Broadcast allows a client to send messages, and multiple receivers to receive the messages.--The broadcasted messages are ephemeral. They are not persisted to the database and are directly relayed through the Realtime server. This is ideal for sending information like mouse moments where latency is important, but need not be persisted.--The broadcast JS client methods are supported from supabase-js v2 release candidate.--To broadcast a message:--```js-const { createClient } = require('@supabase/supabase-js')--const supabase = createClient(- process.env.SUPABASE_URL,- process.env.SUPABASE_KEY-)--// The name of the channel can be set to any string.-// Set the same name across both the broadcasting and receiving clients.-const channel = supabase.channel('user1-location', {- configs: {- broadcast: { ack: true },- },-})--// subscribe registers your client with the server-channel.subscribe(async (status) => {- if (status === 'SUBSCRIBED') {- // now you can start broadcasting messages- // sending a new message every second- setInterval(async () => {- const status = await channel.send({- type: 'broadcast',- event: 'location',- payload: { x: Math.random(), y: Math.random() },- })- console.log(status)- }, 1000)- }-})-```--To receive the broadcasted message, run this script in another tab:--```js-const { createClient } = require('@supabase/supabase-js')--const supabase = createClient(- process.env.SUPABASE_URL,- process.env.SUPABASE_KEY-)--// use the same channel name as the client broadcasting the message is using-const channel = supabase.channel('user1-location')--// listen to broadcasts-channel- .on('broadcast', { event: 'location' }, (payload) => console.log(payload))- .subscribe(async (status) => {- if (status === 'SUBSCRIBED') {- console.log(status)- // your callback function will now be called with the received messages- }- })-```diff --git a/apps/reference/docs/guides/realtime/postgres-changes.mdx b/apps/reference/docs/guides/realtime/postgres-cdc.mdxsimilarity index 73%rename from apps/reference/docs/guides/realtime/postgres-changes.mdxrename to apps/reference/docs/guides/realtime/postgres-cdc.mdxindex e9f01b06460..f8ca7c4728b 100644--- a/apps/reference/docs/guides/realtime/postgres-changes.mdx+++ b/apps/reference/docs/guides/realtime/postgres-cdc.mdx@@ -1,16 +1,20 @@----id: postgres-changes-title: Postgres Changes-description: Getting started with Realtime's Postgres Changes feature+id: postgres-cdc+title: Postgres CDC+description: Getting started with Realtime's Postgres CDC feature----Supabase Postgres Changes listen for database changes and sends them to clients. Clients are required to subscribe with a JWT dictating which changes they are allowed to receive based on the database's [Row Level Security](/docs/guides/auth/row-level-security).+Realtime's Postgres Change Data Capture (CDC) feature listens for database changes and sends them to clients. Clients are required to subscribe with a JWT dictating which changes they are allowed to receive based on the database's [Row Level Security](/docs/guides/auth/row-level-security).-:::cautionAnyone with access to a valid JWT signed with the project's JWT secret is able to listen to your database's changes, unless tables have [Row Level Security](/docs/guides/auth/row-level-security) enabled and policies in place.++Clients can choose to receive `INSERT`, `UPDATE`, `DELETE`, or `*` (all) changes for all changes in a schema, a table in a schema, or a column's value in a table. Your clients should only listen to tables in the `public` schema and you must first enable the tables you want your clients to listen to.++:::caution+Postgres CDC works out of the box for tables in the `public` schema. We do not yet recommend attempting to listen to tables in private schemas due to security concerns and additional permission requirements.:::-Clients can choose to receive `INSERT`, `UPDATE`, `DELETE`, or `*` (all) changes for all changes in a schema, a table in a schema, or a column's value in a table.Your clients can only listen to tables in the `public` schema and you must first enable the tables you want your clients to listen to. You can do this in the [Replication](https://app.supabase.com/project/_/database/replication) section in the Dashboard or with the [SQL editor](https://app.supabase.com/project/_/sql):+You can do this in the [Replication](https://app.supabase.com/project/_/database/replication) section in the Dashboard or with the [SQL editor](https://app.supabase.com/project/_/sql):```sqlbegin;diff --git a/apps/reference/docs/guides/realtime/presence.mdx b/apps/reference/docs/guides/realtime/presence.mdxdeleted file mode 100644index f98b99924d6..00000000000--- a/apps/reference/docs/guides/realtime/presence.mdx+++ /dev/null@@ -1,46 +0,0 @@-----id: presence-title: Presence-description: Getting started with Realtime's presence feature------Supabase Presence stores and synchronize shared state across clients. Presence is very similar to Broadcast, except that the state is “persisted” in the Channel so that new joiners can immediately get the state without waiting for another user to broadcast a message.--The `sync` event is triggered whenever the shared state changes. The `join` event is triggered when a new client joins the channel and `leave` when a client leaves.--Each client can use the `track` method to store an object in the shared state. Each client can only track one object in the shared state. If `track` is called again by the same client, then the new object will overwrite the previously tracked object in the shared state.--The presence JS client methods are supported from supabase-js v2 release candidate.--```js-const { createClient } = require('@supabase/supabase-js')--const supabase = createClient(- process.env.SUPABASE_URL,- process.env.SUPABASE_KEY-)--const channel = supabase.channel('online-users')--function getRandomUser() {- const users = ['Alice', 'Bob', 'Mallory', 'Inian']- return users[Math.floor(Math.random() * users.length)]-}--channel- .on('presence', { event: 'sync' }, () => {- console.log('currently online users', channel.presenceState())- })- .on('presence', { event: 'join' }, ({ newPresences }) => {- console.log('new users have joined', newPresences)- })- .on('presence', { event: 'leave' }, ({ leftPresences }) =>- console.log('users have left', leftPresences)- )- .subscribe(async (status) => {- if (status === 'SUBSCRIBED') {- const status = await channel.track({ user_name: getRandomUser() })- console.log(status)- }- })-```diff --git a/apps/reference/docs/guides/realtime/quickstart.mdx b/apps/reference/docs/guides/realtime/quickstart.mdxnew file mode 100644index 00000000000..e099abd3a46--- /dev/null+++ b/apps/reference/docs/guides/realtime/quickstart.mdx@@ -0,0 +1,258 @@+---+id: quickstart+title: Realtime Quickstart+description: Getting started with Realtime's Features+sidebar_label: Quickstart+---++Learn how to build [multiplayer.dev](https://multiplayer.dev), a collaborative app that demonstrates Broadcast, Presence, and Postgres CDC using [Realtime](/docs/guides/realtime).++<div class="video-container">+ <iframe+ src="https://www.youtube-nocookie.com/embed/BelYEMJ2N00"+ frameBorder="1"+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"+ allowFullScreen+ ></iframe>+</div>++## Install `supabase-js` Client++```bash+npm install @supabase/supabase-js+```++## Cursor Positions++[Broadcast](/docs/guides/realtime#broadcast) allows a client to send messages and multiple clients to receive the messages. The broadcasted messages are ephemeral. They are not persisted to the database and are directly relayed through the Realtime servers. This is ideal for sending information like cursor positions where minimal latency is important, but persisting them is not.++In [multiplayer.dev](https://multiplayer.dev), client's cursor positions are sent to other clients in the room. However, cursor positions will be randomly generated for this example.++You need to get the public `anon` access token from your project's [API settings](https://app.supabase.com/project/_/settings/api). Then you can set up the Suapbase client and start sending a client's cursor positions to other clients in channel `room1`:++```js+const { createClient } = require('@supabase/supabase-js')++const supabase = createClient(+ 'https://your-project-ref.supabase.co',+ 'anon-key',+ {+ realtime: {+ params: {+ eventsPerSecond: 10,+ },+ },+ }+)++// Channel name can be any string.+// Create channels with the same name for both the broadcasting and receiving clients.+const channel = supabase.channel('room1')++// Subscribe registers your client with the server+channel.subscribe((status) => {+ if (status === 'SUBSCRIBED') {+ // now you can start broadcasting cursor positions+ setInterval(() => {+ channel.send({+ type: 'broadcast',+ event: 'cursor-pos',+ payload: { x: Math.random(), y: Math.random() },+ })+ console.log(status)+ }, 100)+ }+})+```++:::info+JavaScript client has a default rate limit of 1 Realtime event every 100 milliseconds that's configured by `eventsPerSecond`.+:::++Another client can subscribe to channel `room1` and receive cursor positions:++```js+// Supabase client setup++// Listen to broadcast messages.+supabase+ .channel('room1')+ .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload))+ .subscribe((status) => {+ if (status === 'SUBSCRIBED') {+ // your callback function will now be called with the messages broadcast by the other client+ }+ })+```++:::info+`type` must be `broadcast` and the `event` must match for clients subscribed to the channel.+:::++## Roundtrip Latency++You can also configure the channel so that the server must return an acknowledgement that it received the `broadcast` message. This is useful if you want to measure the roundtrip latency:++```js+// Supabase client setup++const channel = supabase.channel('calc-latency', {+ config: {+ broadcast: { ack: true }+ }+})++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED) {+ const begin = performance.now()++ await channel.send({+ type: 'broadcast',+ event: 'latency',+ payload: {},+ })++ const end = performance.now()++ console.log(`Latency is ${end - begin} milliseconds`)+ }+ })+```++## Track and display which users are online++[Presence](/docs/guides/realtime#presence) stores and synchronize shared state across clients. The `sync` event is triggered whenever the shared state changes. The `join` event is triggered when new clients join the channel and `leave` event is triggered when clients leave.++Each client can use the channel's `track` method to store an object in shared state. Each client can only track one object, and if `track` is called again by the same client, then the new object overwrites the previously tracked object in the shared state. You can use one client to track and display users who are online:++```js+// Supabase client setup++const channel = supabase.channel('online-users', {+ config: {+ presence: {+ key: 'user1',+ },+ },+})++channel.on('presence', { event: 'sync' }, () => {+ console.log('Online users: ', channel.presenceState())+})++channel.on('presence', { event: 'join' }, ({ newPresences }) => {+ console.log('New users have joined: ', newPresences)+})++channel.on('presence', { event: 'leave' }, ({ leftPresences }) => {+ console.log('Users have left: ', newPresences)+})++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ const status = await channel.track({ online_at: new Date().toISOString() })+ console.log(status)+ }+})+```++Then you can use another client to add another user to the channel's Presence state:++```js+// Supabase client setup++const channel = supabase.channel('online-users', {+ config: {+ presence: {+ key: 'user2',+ },+ },+})++// Presence event handlers setup++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ const status = await channel.track({ online_at: new Date().toISOString() })+ console.log(status)+ }+})+```++If a channel is set up without a presence key, the server generates a random UUID. `type` must be `presence` and `event` must be either `sync`, `join`, or `leave`.++## Insert and Receive Persisted Messages++[Postgres Change Data Capture (CDC)](/docs/guides/realtime#postgres-cdc) enables your client to insert, update, or delete database records and send the changes to clients. Create a `messages` table to keep track of messages created by users in specific rooms:++```sql+create table messages (+ id serial primary key,+ message text,+ user_id text,+ room_id text,+ created_at timestamptz default now()+)++alter table messages enable row level security;++create policy "anon_ins_policy"+ON messages+for insert+to anon+with check (true);++create policy "anon_sel_policy"+ON messages+for select+to anon+using (true);+```++If it doesn't already exist, create a `supabase_realtime` publication and add `messages` table to the publication:++```sql+begin;+ -- remove the supabase_realtime publication+ drop publication if exists supabase_realtime;++ -- re-create the supabase_realtime publication with no tables and only for insert+ create publication supabase_realtime with (publish = 'insert');+commit;++-- add a table to the publication+alter publication supabase_realtime add table messages;+```++You can then have a client listen for changes on the `messages` table for a specific room and send and receive persisted messages:++```js+// Supabase client setup++const channel = supabase.channel('db-messages')++const roomId = 'room1'+const userId = 'user1'++channel.on(+ 'postgres-changes',+ {+ event: 'INSERT',+ schema: 'public',+ table: 'messages',+ filter: `room_id=eq.${roomId}`,+ },+ (payload) => console.log(payload)+)++channel.subscribe(async (status) => {+ if (status === 'SUBSCRIBED') {+ const res = await supabase.from('messages').insert({+ room_id: roomId,+ user_id: userId,+ message: 'Welcome to Realtime!',+ })+ console.log(res)+ }+})+```diff --git a/apps/reference/nav/_referenceSidebars.js b/apps/reference/nav/_referenceSidebars.jsindex 740a0482b85..0234ea1bf78 100644--- a/apps/reference/nav/_referenceSidebars.js+++ b/apps/reference/nav/_referenceSidebars.js@@ -164,9 +164,8 @@ const sidebars = {collapsed: true,items: ['guides/realtime',- 'guides/realtime/broadcast',- 'guides/realtime/presence',- 'guides/realtime/postgres-changes',+ 'guides/realtime/quickstart',+ 'guides/realtime/postgres-cdc',],},{diff --git a/apps/www/lib/redirects.js b/apps/www/lib/redirects.jsindex 7cadf632c47..078cce07d4d 100644--- a/apps/www/lib/redirects.js+++ b/apps/www/lib/redirects.js@@ -1313,6 +1313,21 @@ module.exports = [source: '/docs/guides/realtime/overview',destination: '/docs/guides/realtime',},+ {+ permanent: true,+ source: '/docs/guides/realtime/broadcast',+ destination: '/docs/guides/realtime#broadcast',+ },+ {+ permanent: true,+ source: '/docs/guides/realtime/presence',+ destination: '/docs/guides/realtime#presence',+ },+ {+ permanent: true,+ source: '/docs/guides/realtime/postgres-changes',+ destination: '/docs/guides/realtime/postgres-cdc',+ },{permanent: true,source: '/docs/reference/javascript/next/migration-guide',