Skip to content

docs: mutating the response in the server handle function #11883

Closed
@hyunbinseo

Description

@hyunbinseo

Describe the bug

The example from the server hooks documentation can cause the following error:

TypeError: immutable
at _Headers.set (node:internal/deps/undici/undici:2180:17)
at Object.handle (/src/hooks.server.ts:3:19)

docs: issue since setting headers to ALL responses in the handle function seems dangerous.

Reproduction

// src/routes/+server.ts
export const GET = ({ url }) => Response.redirect(`${url.origin}/${Date.now()}`);
// src/hooks.server.ts
export const handle = async ({ event, resolve }) => {
  const response = await resolve(event);
  response.headers.set('x-custom-header', 'potato');

  return response;
};
pnpm dev --open

Simpler reproduction with identical error:

Response.redirect('https://kit.svelte.dev/').headers.set('x-custom-header', 'potato');

Logs

No response

System Info

System:
  OS: macOS 14.2.1
  CPU: (10) arm64 Apple M1 Pro
  Memory: 40.55 MB / 16.00 GB
  Shell: 5.9 - /bin/zsh
Binaries:
  Node: 20.11.1 - ~/.volta/tools/image/node/20.11.1/bin/node
  npm: 10.2.4 - ~/.volta/tools/image/node/20.11.1/bin/npm
  pnpm: 8.15.3 - ~/.volta/bin/pnpm
Browsers:
  Chrome: 121.0.6167.184
  Edge: 121.0.2277.128
  Safari: 17.2.1
npmPackages:
  @sveltejs/adapter-auto: ^3.0.0 => 3.1.1 
  @sveltejs/kit: ^2.0.0 => 2.5.1 
  @sveltejs/vite-plugin-svelte: ^3.0.0 => 3.0.2 
  svelte: ^4.2.7 => 4.2.11 
  vite: ^5.0.3 => 5.1.4

Severity

annoyance

Additional Information

Removing a response header as a solution:

Response.redirect() spec does not allow modifying the header:

Adding a try-catch block can be a viable documentation fix.

try {
  response.headers.delete('link');
} catch {
  // TypeError: immutable
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions