sveltejs / kit

web development, streamlined
https://svelte.dev/docs/kit
MIT License
18.69k stars 1.93k forks source link

Add an option to distinguish between current navigation load event and `preloadData` load event in server hooks #12559

Open filipwiniarski opened 2 months ago

filipwiniarski commented 2 months ago

Describe the problem

I'm implementing server-side analytics, and I'm using load functions to report user navigation. Some page:

export const load = (event) => {
  event.locals.trackNavigation(event);
};

The problem is some pages do preloadData which then results in multiple navigation events, even though user navigated from one page to another. Client-side tracking is not an option in my case. I wanted to differentiate events in the trackNavigation function, but I couldn't find any determining factor to distinguish navigation from preloading.

I've looked up differences in server hooks events, load functions events, client hooks. I also tried to intercept fetch requests in a service worker to maybe differentiate fetch requests there, but I couldn't find a way to spot a difference.

The very only situation in which I could tell which one is which is the initial session request, which does not include data.json in the pathname. Later, each request contains the data.json with an invalidation parameter.

Describe the proposed solution

Alternatives considered

My goal is to implement server-side tracking. If there's any other option to do it while having preloadData functions in pages and layouts I'd be happy to change the approach.

Importance

would make my life easier

Additional Information

No response

filipwiniarski commented 2 months ago

So currently, as a workaround, I'm setting pathname property in service worker via postMessage on beforeNavigate. Then I'm setting a pathname header that the server can read and filter out unmatching data requests. The drawback is I had to do a hacky (to my taste) line to detect the very first request, as it of course runs before client/service worker. I would love to find an easier way though 🙏 The complexity of my approach just to implement server-side navigation tracking seems overwhelming.