pixelmund / svelte-kit-cookie-session

⚒️ Encrypted "stateless" cookie sessions for SvelteKit
MIT License
184 stars 12 forks source link

init() doesn't set initial cookie until set() or update() is called #54

Closed dmoebius closed 1 year ago

dmoebius commented 1 year ago

I'd like to initialize my session id in the sessionHandler in hooks.server.ts:

export const handle = handleSession({
    key: 'session',
    init: (event) => ({
        id: crypto.randomUUID(),
    }),
    ...

In my top-level +layout.server.ts I have:

export const load = (async ({url, cookies, locals}) => {
    ....
    return {
        locale,
        locales,
        session: locals.session.data,
    }
})

Even though locals.session.data contains a freshly created id, the cookie is not set. The handler doesn't return a "Set-Cookie" header.

It only sets a cookie if I add a dummy assignment, such as:

    await locals.session.update(({id}) => ({id}))

but this updates the cookie on each request. (Might be required for rolling=true anyway.)

I would like to have the cookie set initially without such dummy assignment.

Btw.: thanks for such a great project! :+1:

dmoebius commented 1 year ago

I could of course add this to +layout.server.ts:

    if (locals.session.data.id === undefined) {
        await locals.session.update(() => ({id: crypto.randomUUID()}))
    }

But if I had multiple independent toplevel roots, then I'd have to add this to each toplevel +layout.server.ts for each root. (Not a very common scenario, I admit.)

pixelmund commented 1 year ago

You can now use the saveUninitialized: true option to save the output of the init command if no session is saved.