Inconsistent behaviour when changing headers of generated response
Describe the bug
When setting headers of an already generated response through event.setHeaders and event.cookies.set the behaviour is inconsistent.
event.cookies.set throws an error, while event.setHeaders does not. Based on the code at https://github.com/sveltejs/kit/blob/c749e85d2502d5eac03f739c8f18a2f3a4dcb13e/packages/kit/src/runtime/server/respond.js#L541-L547 I would assume they are both supposed to fail.
Server logs when going to http://localhost:5173/a/b in the reproduction repo I've attached shows the issue:
starting /a/b
redirect
resolved /a/b
would error layout event.setHeaders: false
would error layout event.cookies.set: true
Since there is no indirection in front of these functions destructuring like the following, would prevent event.cookies.set from erroring as well:
export const load: LayoutServerLoad = async ({ setHeaders, cookies: { set }}) => {
Additionally, I would suggest adding some mechanism for checking this state, besides checking the toString of event.cookies.set. Something like event.responseGenerated() or event.headersSent(), since in many cases, unnecessary work can be completely skipped if the event has already been handled / responded to. Let me know if you want me to submit that as a separate feature request.
Reproduction
Reproduction repository: https://github.com/evestera/sveltekit-headers-sent-repro
Commit of changes from "skeleton" project: https://github.com/evestera/sveltekit-headers-sent-repro/commit/a37b3b1c6b4997b08575028499da587da6121d5b
src/routes/a/b/+page.server.ts redirects, while src/routes/a/+layout.server.ts inspects the two functions after a short delay.
Logs
No response
System Info
System:
OS: macOS 14.2.1
CPU: (8) arm64 Apple M1 Pro
Memory: 73.73 MB / 16.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 21.6.1 - ~/Library/Caches/fnm_multishells/76568_1707148995605/bin/node
Yarn: 1.22.19 - /opt/homebrew/bin/yarn
npm: 10.2.4 - ~/Library/Caches/fnm_multishells/76568_1707148995605/bin/npm
pnpm: 7.30.3 - /opt/homebrew/bin/pnpm
bun: 1.0.20 - ~/.bun/bin/bun
Browsers:
Brave Browser: 116.1.57.47
Chrome: 121.0.6167.139
Safari: 17.2.1
npmPackages:
@sveltejs/adapter-auto: ^3.0.0 => 3.1.1
@sveltejs/kit: ^2.0.0 => 2.5.0
@sveltejs/vite-plugin-svelte: ^3.0.0 => 3.0.2
svelte: ^4.2.7 => 4.2.10
vite: ^5.0.3 => 5.0.12
Severity
annoyance
Additional Information
No response