Expose add_cookies_to_headers
via cookies.write
#11712
Labels
feature / enhancement
New feature or request
add_cookies_to_headers
via cookies.write
#11712
Describe the problem
This has been discussed before in #8409 and #7611, but I think we have a bit of a different use case here.
We're working on a cookie manager library that layers on some additional niceties to the cookies API in SvelteKit (e.g. defining and validating the shape of cookies, handling serializing to/from JSON and base64, ability to manage and write cookies both server side and client side, etc). The manager allows libraries to define their own cookies and then export them, so you can have shared cookies between different libraries more easily:
This is all typed and really nice to work with. The tricky part is that we can't really use it in both hooks and
+page.server.ts
contexts, because in hooks we can't use thecookies
API, but in+page.server.ts
we must use thecookies
API, there's no way for us to addset-cookies
headers otherwise. Currently it seems like the only option is to have a new type of writer or some other option for changing the behavior in hooks vs pages.Describe the proposed solution
I feel like this could be remedied by exposing the
add_cookies_to_headers
function on thecookies
API. This would only be callable once per request, it would throw if called a second time. The purpose would be so that hooks that return custom responses can optionally choose to write out the added cookies manually at some point.Alternatives considered
We could allow users to add the
set-cookie
header via theheaders
API. Our library currently outputs theset-cookie
value as a string, so it would be easy to add it that way, but it does seem a bit hacky.We could also always serialize cookies to all responses, but this would be tricky. I think there are a couple ways to approach this:
Response
objects inhandle
#7611 this would result in a gap between cookies being added and hooks resolving, so hooks would no longer see any added cookies. This would also be a breaking API change so probably not worth it.resolve
(e.g. resolve has not been called). Throw an error otherwise. This would work well, but would mean that users can't callresolve
, ignore the response, and then set cookies, which would be a weird edge case.resolve
cookies to be ignored by hooks, but would be more complex and require some additional bookkeeping to flush the cookies between sets.Importance
nice to have
Additional Information
No response
The text was updated successfully, but these errors were encountered: