Search code examples
cookiessveltesession-cookiessveltekit

Sveltekit Session Cookie Read / Write


I am working on an app powered by Sveltekit that provides login sessions. When the user successfully logs in, I redirect them to their user page as follows:

cookies.set('session', token, {
    path: '/',
    httpOnly: true,
    sameSite: 'strict',
    maxAge: 60 * 60 * 24 * 30 //month
});

throw redirect(302, `/${user.login}`);

In the +page.server.ts of the user profile, I validate the session cookie as follows:

export const load = (async ({ params, cookies }) => {
    const session = cookies.get('session');
    if (!session) throw error(401, 'Unauthorized');

    return { "success" };
}) satisfies PageServerLoad;

The problem now is that the validation fails after the redirect. And only when a reload happens, the session cookie gets validated correctly. My guess is that the cookie.set() method is not yet executed when the redirect happens.

Question: The cookie validation on the +page.server.ts happens to fast. How to wait for the cookie to be set or otherwise how to validate the cookie later on?


Solution

  • Thanks to the Svelte community over on Discord, I got my answer.

    The load function might run before the cookie is set.

    It is best to validate the cookie in the hooks.server.js file instead of in the load function.

    A good article that I used to set up the validation: https://dev.to/brewhousedigital/secure-authentication-in-svelte-using-hooks-k5j