One of the most powerful features of Supabase Realtime is its ability to filter the data you receive. Instead of subscribing to every single change on a table, you can specify conditions to get only the updates that are relevant to your application's current state. This not only makes your application more efficient by reducing unnecessary data transfer and processing but also simplifies your client-side logic.
Supabase Realtime subscriptions allow you to apply filters using the eq (equals), neq (not equals), lt (less than), lte (less than or equal to), gt (greater than), gte (greater than or equal to), in (in array), and is (is null or not null) operators. These are the same operators you're likely familiar with from Supabase's query builder.
To add filters to your realtime subscription, you simply chain the .filter() method onto your from() call before subscribing. You pass the column name, the operator, and the value you want to filter by. You can even chain multiple .filter() calls to create more complex conditions.
const channel = supabase.channel('public:todos:completed=eq.true', {
config: {
postgres_changes: {
filter: 'completed=eq.true'
}
}
});
channel.subscribe((status) => {
if (status === 'SUBSCRIBED') {
console.log('Subscribed to completed todos!');
}
});In this example, we're subscribing to changes only on the todos table where the completed column is true. This is perfect for a task list application where you might want to show only active or completed tasks separately.
You can also filter based on multiple conditions. For instance, you might want to get all todos that are not completed and were created after a specific date. You can achieve this by chaining multiple .filter() methods.
const channel = supabase.channel('public:todos:incomplete_and_recent', {
config: {
postgres_changes: {
filter: 'completed=eq.false,created_at=gt.2023-10-27T00:00:00'
}
}
});
channel.subscribe((status) => {
if (status === 'SUBSCRIBED') {
console.log('Subscribed to incomplete and recent todos!');
}
});