SupabaseS
Supabase•3y ago
smaak

Realtime subscription happens before session

I am making a chat application with sveltekit and I have a component <RealtimeSubscription/>, that subscribes to the db changes.
Everything was working fine until I enabled RLS where only authenticated users can insert to the chat_messages table.

It started to work very inconsistently and I noticed that in my realtime schema on the subscription table the claims_role is sometimes anon. I believe this is because the realtime sub is happening before some auth stuff?

I use supabase auth and I copy and pasted the code from here: https://supabase.com/docs/guides/auth/server-side/creating-a-client?framework=sveltekit&environment=hooks

I am super confused, how does the supabaseClient sometimes know the user is authenticated but sometimes don't?
Here's some code if it helps 🙂

supabase.ts
import { createClient } from "@supabase/supabase-js";
export const supabaseClient = createClient(
    PUBLIC_SUPABASE_URL,
    PUBLIC_SUPABASE_ANON_KEY
)


RealtimeSubscription.svelte
import { supabaseClient } from "$lib/supabase";

onMount(async () => {
    //Don't subscribe if there's no server session  
    if(!$page?.data?.session) return
    let character_channel = supabaseClient.channel("chat_messages_db_changes").on("postgres_changes",
        {
            event: "*",
            schema: "public",
            table : "chat_messages"
        },
        async (payload) => { 
            console.log(payload)
        }).subscribe((status) => {
            console.log("Realtime: " + status)
        });
})
Configure Supabase client to use Cookies
Was this page helpful?