Realtime

Broadcast

Send low-latency messages using the client libs, REST, or your Database.


You can use Realtime Broadcast to send low-latency messages between users. Messages can be sent using the client libraries, REST APIs, or directly from your database.

How Broadcast works#

The way Broadcast works changes based on the channel you are using:

  • REST API: Receives an HTTP request and then sends a message via WebSocket to connected clients
  • Client libraries: Sends a message via WebSocket to the server, and then the server sends a message via WebSocket to connected clients
  • Database: Adds a new entry to realtime.messages where a logical replication is set to listen for changes, and then sends a message via WebSocket to connected clients

For Authorization, we insert a message and try to read it, and rollback the transaction to verify that the Row Level Security (RLS) policies set by the user are being respected by the user joining the channel, but this message isn't sent to the user. You can read more about it in Authorization.

Subscribe to messages#

You can use the Supabase client libraries to receive Broadcast messages.

Initialize the client#

Get the Project URL and key from the project's Connect dialog.

1
import { createClient } from '@supabase/supabase-js'
2
3
const SUPABASE_URL = 'https://<project>.supabase.co'
4
const SUPABASE_KEY = '<sb_publishable_... or anon key>'
5
6
const supabase = createClient(SUPABASE_URL, SUPABASE_KEY)

Receive Broadcast messages#

You can receive Broadcast messages by providing a callback to the channel.

1
// @noImplicitAny: false
2
import { createClient } from '@supabase/supabase-js'
3
const supabase = createClient('https://<project>.supabase.co', '<sb_publishable_... or anon key>')
4
5
// ---cut---
6
// Join a room/topic. Can be anything except for 'realtime'.
7
const myChannel = supabase.channel('test-channel')
8
9
// Simple function to log any messages we receive
10
function messageReceived(payload) {
11
console.log(payload)
12
}
13
14
// Subscribe to the Channel
15
myChannel
16
.on(
17
'broadcast',
18
{ event: 'shout' }, // Listen for "shout". Can be "*" to listen to all events
19
(payload) => messageReceived(payload)
20
)
21
.subscribe()

Send messages#

Broadcast using the client libraries#

You can use the Supabase client libraries to send Broadcast messages.

1
import { createClient } from '@supabase/supabase-js'
2
const supabase = createClient('your_project_url', 'your_supabase_api_key')
3
4
// ---cut---
5
const myChannel = supabase.channel('test-channel')
6
7
/**
8
* Sending a message before subscribing will use HTTP
9
*/
10
myChannel
11
.send({
12
type: 'broadcast',
13
event: 'shout',
14
payload: { message: 'Hi' },
15
})
16
.then((resp) => console.log(resp))
17
18
19
/**
20
* Sending a message after subscribing will use WebSockets
21
*/
22
myChannel.subscribe((status) => {
23
if (status !== 'SUBSCRIBED') {
24
return null
25
}
26
27
myChannel.send({
28
type: 'broadcast',
29
event: 'shout',
30
payload: { message: 'Hi' },
31
})
32
})

Broadcast from the Database#

You can send messages directly from your database using the realtime.send() function:

1
select
2
realtime.send(
3
jsonb_build_object('hello', 'world'), -- JSONB Payload
4
'event', -- Event name
5
'topic', -- Topic
6
false -- Public / Private flag
7
);

You can use the realtime.broadcast_changes() helper function to broadcast messages when a record is created, updated, or deleted. For more details, read Subscribing to Database Changes.

Broadcast using the REST API#

You can send a Broadcast message by making an HTTP request to Realtime servers.

1
curl -v \
2
-H 'apikey: <SUPABASE_TOKEN>' \
3
-H 'Content-Type: application/json' \
4
--data-raw '{
5
"messages": [
6
{
7
"topic": "test",
8
"event": "event",
9
"payload": { "test": "test" }
10
}
11
]
12
}' \
13
'https://<PROJECT_REF>.supabase.co/realtime/v1/api/broadcast'

Broadcast options#

You can pass configuration options while initializing the Supabase Client.

Self-send messages#

By default, broadcast messages are only sent to other clients. You can broadcast messages back to the sender by setting Broadcast's self parameter to true.

1
const myChannel = supabase.channel('room-2', {
2
config: {
3
broadcast: { self: true },
4
},
5
})
6
7
myChannel.on(
8
'broadcast',
9
{ event: 'test-my-messages' },
10
(payload) => console.log(payload)
11
)
12
13
myChannel.subscribe((status) => {
14
if (status !== 'SUBSCRIBED') { return }
15
myChannel.send({
16
type: 'broadcast',
17
event: 'test-my-messages',
18
payload: { message: 'talking to myself' },
19
})
20
})

Acknowledge messages#

You can confirm that the Realtime servers have received your message by setting Broadcast's ack setting to true.

1
import { createClient } from '@supabase/supabase-js'
2
const supabase = createClient('your_project_url', 'your_supabase_api_key')
3
4
// ---cut---
5
const myChannel = supabase.channel('room-3', {
6
config: {
7
broadcast: { ack: true },
8
},
9
})
10
11
myChannel.subscribe(async (status) => {
12
if (status !== 'SUBSCRIBED') { return }
13
14
const serverResponse = await myChannel.send({
15
type: 'broadcast',
16
event: 'acknowledge',
17
payload: {},
18
})
19
20
console.log('serverResponse', serverResponse)
21
})

Use this to guarantee that the server has received the message before resolving channelD.send's promise. If the ack config is not set to true when creating the channel, the promise returned by channelD.send will resolve immediately.

Send messages using REST calls#

You can also send a Broadcast message by making an HTTP request to Realtime servers. This is useful when you want to send messages from your server or client without having to first establish a WebSocket connection.

1
const channel = supabase.channel('test-channel')
2
3
// No need to subscribe to channel
4
5
channel
6
.send({
7
type: 'broadcast',
8
event: 'test',
9
payload: { message: 'Hi' },
10
})
11
.then((resp) => console.log(resp))
12
13
// Remember to clean up the channel
14
15
supabase.removeChannel(channel)

Trigger broadcast messages from your database#

How it works#

Broadcast Changes allows you to trigger messages from your database. To achieve it, Realtime directly reads your Write-Ahead Log (WAL) file using a publication against the realtime.messages table. Whenever a new insert occurs, a message is sent to connected users.

It uses partitioned tables per day, which allows performant deletion of your previous messages by dropping the physical tables of this partitioned table. Tables older than 3 days are deleted.

Broadcasting from the database works like a client-side broadcast, using WebSockets to send JSON payloads. Realtime Authorization is required and enabled by default to protect your data.

Broadcast Changes provides two functions to help you send messages:

  • realtime.send() inserts a message into realtime.messages without a specific format.
  • realtime.broadcast_changes() inserts a message with the required fields to emit database changes to clients. This helps you set up triggers on your tables to emit changes.

Broadcasting a message from your database#

The realtime.send() function provides the most flexibility by allowing you to broadcast messages from your database without a specific format. This allows you to use database broadcast for messages that aren't necessarily tied to the shape of a Postgres row change.

1
SELECT realtime.send (
2
'{}'::jsonb, -- JSONB Payload
3
'event', -- Event name
4
'topic', -- Topic
5
FALSE -- Public / Private flag
6
);

Broadcast record changes#

Setup realtime authorization#

Realtime Authorization is required and enabled by default. To allow your users to listen to messages from topics, create an RLS policy:

1
CREATE POLICY "authenticated can receive broadcasts"
2
ON "realtime"."messages"
3
FOR SELECT
4
TO authenticated
5
USING ( true );

Read Realtime Authorization to learn how to set up more specific policies.

Set up trigger function#

First, set up a trigger function that uses the realtime.broadcast_changes() function to insert an event whenever it is triggered. The event is set up to include data on the schema, table, operation, and field changes that triggered it.

For this example, you're going broadcast events to a topic named topic:<record_id>.

1
CREATE OR REPLACE FUNCTION public.your_table_changes()
2
RETURNS trigger
3
SECURITY DEFINER SET search_path = ''
4
AS $$
5
BEGIN
6
PERFORM realtime.broadcast_changes(
7
'topic:' || NEW.id::text, -- topic
8
TG_OP, -- event
9
TG_OP, -- operation
10
TG_TABLE_NAME, -- table
11
TG_TABLE_SCHEMA, -- schema
12
NEW, -- new record
13
OLD -- old record
14
);
15
RETURN NULL;
16
END;
17
$$ LANGUAGE plpgsql;

The Postgres native trigger special variables used are:

  • TG_OP - the operation that triggered the function
  • TG_TABLE_NAME - the table that caused the trigger
  • TG_TABLE_SCHEMA - the schema of the table that caused the trigger invocation
  • NEW - the record after the change
  • OLD - the record before the change

You can read more about them in this guide.

Set up trigger#

Next, set up a trigger so the function runs whenever your target table has a change.

1
CREATE TRIGGER broadcast_changes_for_your_table_trigger
2
AFTER INSERT OR UPDATE OR DELETE ON public.your_table
3
FOR EACH ROW
4
EXECUTE FUNCTION your_table_changes ();

As you can see, it will be broadcasting all operations so our users will receive events when records are inserted, updated or deleted from public.your_table .

Listen on client side#

Finally, client side will requires to be set up to listen to the topic topic:<record id> to receive the events.

1
const gameId = 'id'
2
await supabase.realtime.setAuth() // Needed for Realtime Authorization
3
const changes = supabase
4
.channel(`topic:${gameId}`)
5
.on('broadcast', { event: 'INSERT' }, (payload) => console.log(payload))
6
.on('broadcast', { event: 'UPDATE' }, (payload) => console.log(payload))
7
.on('broadcast', { event: 'DELETE' }, (payload) => console.log(payload))
8
.subscribe()

Broadcast replay#

How it works#

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 (for example, 1697472000000), 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.
1
const config = {
2
private: true,
3
broadcast: {
4
replay: {
5
since: 1697472000000, // Unix timestamp in milliseconds
6
limit: 10
7
}
8
}
9
}
10
const channel = supabase.channel('main:room', { config })
11
12
// Broadcast callback receives meta field
13
channel.on('broadcast', { event: 'position' }, (payload) => {
14
if (payload?.meta?.replayed) {
15
console.log('Replayed message: ', payload)
16
} else {
17
console.log('This is a new message', payload)
18
}
19
// ...
20
})
21
.subscribe()

When to use Broadcast replay#

A few common use cases for Broadcast Replay include:

  • Displaying the most recent messages from a chat room
  • Loading the last events that happened during a sports event
  • Ensuring users always see the latest events after a page reload or network interruption
  • Highlighting the most recent sections that changed in a web page