Replies: 1 comment
-
I've just stumbled upon this issue as well. The docs don't show any examples of setting headers in a layout load, only in a page load. I found that if the erroring page and the error page share the same layout with the load function setting headers the "Error: "Cache-control" header is already set" would show. I think this is due to that specific layout running twice in the case of an error. A structure like the following seems to work without issue. I also tried testing the difference between setting headers in layout load and server hooks. With Vite preview the cache-control headers seem to apply only to the document in the bundled application with both setups. I agree that this seems to be something lacking documentation especially with it's importance to Auth. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
TLDR: What is the recommended place to set headers in sveltekit? Server hooks or server load functions (e.g. layout)?
We recently had a problematic occurrence where a user logged out and then after clicking the back button, he could still see the previous page as it was cached. To prevent this behavior, we introduced the
Cache-Control: no-store
header at the root+layout.server.ts
of our app, as such:A few weeks later, I noticed that if a certain page had an error (any kind of exception), I would not see the error in the console during server-side rendering (SSR), but instead the following message masking the true error.
After some research, I found out that when an error occurs during server-side rendering (SSR), SvelteKit internally sets certain headers, including the cache-control header. When the load function tries to set the cache-control header again during an error state, it leads to a conflict, resulting in a misleading error message.
To overcome this problem, I resorted to using
hooks.server.ts
so the handle hook runs before any errors are processed and allows me to set headers globally without conflicting with SvelteKit's internal error handling. But server hooks and load functions do two very different things and I don't want to risk caching anything else other than the pages.At the same time, I've also seen SvelteKit suggesting in the docs the usage of
load
functions to set headers which seems to be problematic.So my question is: Is this the recommended place to set this kind of header?
Beta Was this translation helpful? Give feedback.
All reactions