Search code examples
sveltesveltekit

How can I access data.user variables in lib/components in sveltekit that are already defined in layout.server.ts?


I am using Sveltekit 4, with Supabase SSR for authentication. I can successfully access user session data from any route pages, but not from any components.

Here is my src/routes/+layout.server.ts

import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ locals: { getSession } }) => {
    const session = await getSession();
    return {        
        session
    };
};

and my src/routes/+page.svelte can successfully access a logged in user's details:

<script lang="ts">
    export let data;
</script>

{#if data.user}
    <h2>Welcome {data.user.email}</h2>
{/if}

how can I also access this logged in user detail in src/lib/components/Navigation.svelte where I would want the following to work:

<script lang="ts">
    export let data: any;
</script>

<h2>Not logged on</h2>

{#if data.user}
<h2>{data.user.email}</h2>
{/if}

My understanding is that data in layout.server.ts would be available in all routes and components, how do I make it available in my component?


Solution

  • You can pass data through prop down to component or use store. When it comes to user session you can use $page store:

    // src/routes/+layout.server.ts load function
    return {        
        session
    }
    
    // your +page.svelte
    import { page } from '$app/stores'
    // access session with
    $page.data.session
    

    As we learned earlier, Svelte stores are a place to put data that doesn't belong to an individual component.

    SvelteKit makes three readonly stores available via the $app/stores module — page, navigating and updated. The one you'll use most often is page, which provides information about the current page

    https://learn.svelte.dev/tutorial/page-store