Client-side useSession() not updating upon sign-in

I'm using SvelteKit form actions to handle sign-in (with the new sveltekitCookies plugin), but after I sign in, my layout doesn't update until I refresh the page. Looking at dev tools, the cookie is set properly right after sign-in. Any help would be appreciated!

+page.server.ts
import { auth } from '$lib/auth';
import { redirect, fail } from '@sveltejs/kit';
import { APIError } from 'better-auth/api';

export const load = async ({ request }) => {
    const session = await auth.api.getSession({
        headers: request.headers
    });
    if (session) {
        redirect(302, '/');
    }
};
export const actions = {
    default: async ({ request }) => {
        const data = await request.formData();
        const email = data.get('email') as string;
        const password = data.get('password') as string;

        try {
            await auth.api.signInEmail({
                body: {
                    email,
                    password
                },
                headers: request.headers,
            });    
        } catch (error) {            
            if (error instanceof APIError) {
                console.error('Sign in APIError:', error);
                return fail(400, {
                    error: error.message || 'Failed to sign in'
                });
            }
            
            console.error('Unexpected sign in error:', error);
            return fail(500, {
                error: 'An unexpected error occurred'
            });
        }
        return redirect(302, "/");
    }
};


+layout.svelte (root)
<script lang="ts">
    import '../app.css';
    import { authClient } from '$lib/auth-client';

    let { children } = $props();
    
    const session = authClient.useSession();
    $inspect($session.data); // displays null after signing in
</script>


{#if $session.data}
...
{:else}
...
{/if}
Solution
if you sign in on the server side, useSession doesn't know that. If you did the signIn using authClient, useSession would know.
What I would recommend is after calling the server action, on the client call refetch:
const { refetch } = authClient.useSession();
//.     ^
Was this page helpful?