sveltesveltekit

Sveltekit: Fetch user details on every page


When the user logs in I store the sessionID and user details (name, avatar, ...) in cookies. In my website's header I have something along the lines of:

<script>
let user = undefined;
onMount(() => { user = getCurrentUser(); })
</script>

{#if user}
Hello {user.name}
{:else}
<a href="/login">Login</a>
{/if}

Unfortunately, after I login and redirect the user to the main page the main page first shows the "Login" button still (even though the cookies are present) and after a second updates and correctly shows the "Hello XYZ" element.

I think the delay comes from the onMount(...) which doesn't execute immediately. I think I have to read the user details on the server from the cookies and make them accessible in Svelte's load function. However, how do I do that for every single page given that I need to know the user state in the website's header. I could duplicate this logic for all my +page.server.ts scripts but that doesn't seem ideal. I am looking for something a la +layout.server.ts (which I know doesn't exist)


Solution

  • +layout.server.ts does exist, so yes, you can use that.

    Data from the layout's load function is merged with the data from individual pages.

    Note that if you are also using the fetching of the current user data as part of your authentication mechanism, data loaded by pages will be loaded in parallel/independently by default and thus not be protected by the layout logic. You can prevent this by waiting for parent data in the pages, but this is prone to accidentally being omitted in one of the routes.

    A more resilient approach would be to use a handle hook, which runs before every request for the auth part. This hook can set data on the event's locals to pass data to server load functions.