Skip to content

hooks caching makes testing difficult #15687

@simonsarris

Description

@simonsarris

Describe the bug

hooks.sever.ts and hooks.ts cache routes, which is a good idea, but during testing this can makes mistakes (such as dropping query params) fiendishly difficult to detect. Using new query params each time sorta solves this, but is not tenable for a lot of query param uses.

Reproduction

You can reproduce with a hooks.server.ts like this:

// hooks.server.ts
import { redirect } from '@sveltejs/kit';

export const handle = async ({ event, resolve }) => {
  const path = event.url.pathname;
  let params = event.url.searchParams.toString();
  if (params) params = '?' + params;
  console.log(path, params);
  // Break params on purpose:
  params = '';

  if (path.endsWith('index.html')) {
    redirect(301, path.split('/index.html')[0] + params);
  }

  if (path.endsWith('.html')) {
    redirect(301, path.split('.html')[0] + params);
  }
  const response = await resolve(event);
  return response;
};

Take note of // Break params on purpose:, the point here is that this hooks mistakenly strips params. Then you can make any old route, I have /blah with for the sake of testing:

// +page.server.ts
export const load = async ({ url }) => {
  console.log(url);
  console.log(`params: ${url.searchParams}`);
};

So if you go to
http://localhost:5173/blah.html?a=999
you will get
http://localhost:5173/blah

That's bad. So you fix your mistake:
// params = ''; // whoops lets stop breaking params

Then if you go to:
http://localhost:5173/blah.html?a=999
you will still get
http://localhost:5173/blah

However on a totally new param like blah.html?a=222 you will correctly get blah?a=222

It is difficult to realize that caching is doing this (though the docs do mention it), but it actually gets even weirder if you have both a hooks.server.ts and a hooks.ts, and one or both of them are doing the wrong thing. Of course one should never write the wrong code! But if you do, it becomes especially difficult to fix the problem.

Logs

System Info

System:
    OS: Windows 11 10.0.26100
    CPU: (12) x64 AMD Ryzen 5 5600 6-Core Processor
    Memory: 18.61 GB / 31.93 GB
  Binaries:
    Node: 22.13.1 - C:\Program Files\nodejs\node.EXE
    npm: 11.2.0 - C:\Program Files\nodejs\npm.CMD
    pnpm: 8.12.1 - ~\AppData\Roaming\npm\pnpm.CMD
  Browsers:
    Edge: Chromium (131.0.2903.146)
    Internet Explorer: 11.0.26100.1882

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions