j4w8n/sb-auth-helper

Pass the session to a navigation component inside the root +layout.svelte

Closed this issue · 2 comments

I have able to setup the basics with Supabase thanks to your repo.

  • Then, I could not succeed to pass the session to a component, to display the user's email if any session or a login button.

  • Basically, my app is structured like this :

/src
   /routes
      +layout.svelte <=== This file contains a TopBar.svelte component in ./src/lib/components folder.

// /src/+layout.svelte
<script lang="ts">
...
export let data;

let { supabase, session } = data;
$: ({ supabase, session } = data);
</script>

<TopNavBar userEmail={session?.user.email} />

The user email appears for a second then pass to undefined.

Any idea? I've been used to Nuxt but I'm very new to Svelte and Kit.

I'm not sure. I implemented the same thing and it's working. Whenever I'm logged out, it renders as undefined; when logged in, it shows the email.

/* src/lib/Test.svelte */
<script lang="ts">
  export let email: string | undefined
</script>

<p> Email is: {email} </p>
/* src/routes/+layout.svelte */
<script lang="ts">
...
import Test from '../lib/Test.svelte'

export let data

let { supabase, session } = data
$: ({ supabase, session } = data)

...
</script>

<Test email={session?.user.email}/>

Great, I got it to work properly. I'm not sure what the problem was, but I managed it by modifying my dependencies a bit.

  • My project was still using the @supabase/auth-helpers-sveltekit package, which I removed.
  • I also downgraded @supabase/supabase-js to 2.33.1 (previously > 2.38).
  • I have placed @supabase/supabase-js in the dependencies and not in the dev dependencies.
  • I was missing the cached event in the +layout.svelte file.
	let cached_event = "";

	onMount(() => {
		const {
			data: { subscription },
		} = supabase.auth.onAuthStateChange(async (event, _session) => {
			if (_session?.expires_at !== session?.expires_at) {
				invalidate("supabase:auth");
			}

/* Was missing
			if (cached_event && event === cached_event) {
				console.log("same event as last time");
				return;
			}
			cached_event = event;

			if (event === "SIGNED_IN") {
				console.log("recevied new SIGNED_IN event");
				const { data, error } = await supabase.from("messages").select("*");
				console.log("users messages", data, error);
			}
		});
*/
		return () => subscription.unsubscribe();
	});

Thanks for your help!

You're the only working example I found for days for SvelteKit and Supabase.