'How to implement cookie authentication with Sveltekit & Supabase?

I'm fairly new to both SvelteKit & Supabase and have done a bit of experimentation on my own, but I would like to know what is the best way to implement user authentication with both of these technologies.

I currently have the following in my __layout.svelte file so that every page on my web application will have access to the session but I'm not sure how to implement persistent user authentication with a cookie.

If anyone can guide me and future users that would be awesome!

<script>
  import supabase from "$lib/api";
  import { page, session } from '$app/stores';
  import { browser } from '$app/env';

    if(browser){
      $session = supabase.auth.session();
      supabase.auth.onAuthStateChange((event, sesh) => {
        $session = sesh;
      });
    }
</script>


Solution 1:[1]

It is definitely not clear how to do this. I tried to make it easy and put it into a user readable store:

export const user = readable<any>(null, (set) => {

    set(supabase.auth.user());
    const unsubscribe = supabase.auth.onAuthStateChange((_, session) => {
        session ? set(session.user) : set(null);
    });
    return () => {
        unsubscribe.data.unsubscribe();
    }
});

Now you can just use $user anywhere to get the session, or see if there is a session.

J

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan