sveltejs / kit

web development, streamlined
https://svelte.dev/docs/kit
MIT License
18.65k stars 1.93k forks source link

Cookies in universal load function #11828

Open MajorBreakfast opened 8 months ago

MajorBreakfast commented 8 months ago

Describe the problem

Currently cookies are only available in +page.server.ts and +layout.server.ts but not in the universal load variants.

Describe the proposed solution

Make cookies available in universal load(). Only cookies with httpOnly disabled may be accessed, so that the universal load() function behaves the same in whichever environment it is executed.

Alternatives considered

No response

Importance

would make my life easier

Additional Information

No response

dennisvanderweide commented 8 months ago

I wanted to create an issue for this for quite some time now, but kept forgetting to do it. This is something I would enjoy having too. I have been looking at a possible implementation of this.

It's very easy to expose the current server side cookies object in the universal load function and add a client side implementation using document.cookie. But this would lead to different behavior between both environments, because the server has access to HttpOnly cookies, which the client does not.

To keep the same behavior in both environments, you propose to only have access to cookies with HttpOnly disabled, but sadly this is not possible, because this data is not available server side; the only data sent with the request is name=value.

Rich-Harris commented 2 months ago

I'm opposed to this — it sets a precedent that cookies without httpOnly are encouraged, which they are very much not. What is a valid use case?

david-plugge commented 2 months ago

What about naming them unsafeCookies or similar? Or enforcing the user to always set { httpOnly: false } to make it very clear.

You can't set and get cookies in universal load functions currently (you can on the client, but not on the server). I do understand that you dont want to encourage people to use non httpOnly cookies but there are use cases like a theme cookie. In fact the supabase library uses non httpOnly cookies for their authentication and i remember when i was working on their sveltekit adapter we had a hard time making everything work due to not beeing able to modify cookies in universal load functions.

dennisvanderweide commented 2 months ago

@Rich-Harris Authentication is also our exact use case. We are working primarily on SPAs with initial SSR. Right now we need to implement a server side and a client side version of handling authorized requests. Being able to use cookies in the universal load functions would really simplify use cases like this, because you can create a 'universal' flow for this.