Skip to content

Knowing if we are in a client side navigation or direct hit #4447

@jycouet

Description

@jycouet

Describe the problem

Let's try to describe the Feature Request with a small graph:

flowchart TB
    b3-->a2
    subgraph Page Home
    a0[New visitor]-->a1[load server]-->a2[load browser]-->a3[Enjoy the home page]
    style a0 fill:#29B56A,color:#000
    style a3 fill:#254CA0,color:#000
    end
    subgraph Page About
    b0[New visitor]-->b1[load server]-->b2[load browser]-->b3[Enjoy the about page]
    style b0 fill:#29B56A,color:#000
    style b3 fill:#254CA0,color:#000
    end
Loading

As you can see, I have 2 routes: Home and About.
On a direct hit, the load function is executed 2 times once !browser once browser
On navigation from About to Home, the load function of Home is executed 1-time browser

The problem: how can I know in a load function if I'm in a client side navigation or direct hit?

Describe the proposed solution

The best to my mind would be to have something similar to browser like:

import { clientNavigation } from '$app/navigation';

export async function load() {
    console.log(`clientNavigation`, clientNavigation);
    return {};
}

When it's a direct hit, the 2 load functions would have clientNavigation to false.
When it's a client side navigation, the load function would have clientNavigation to true.

Alternatives considered

Workaround I use today:

I have a file clientNavigation.ts

export let clientNavigation = false;

export const setClientNavigation = () => {
	clientNavigation = true;
};

And in __layout.svelte I have

<script lang="ts">
	// Todo: https://github.com/sveltejs/kit/issues/4048#issuecomment-1073577686
	import { afterNavigate } from '$app/navigation';
	import { setClientNavigation } from '$lib/clientNavigation';

	afterNavigate(() => setClientNavigation());
</script>

And now I can use clientNavigation value to know if I'm in a client side navigation or direct hit.

Importance

would make my life easier

Additional Information

This would allow nice scenarios for my library https://github.com/jycouet/kitql awaiting or not to fill stores depending on the situation.

I would be happy to contribute (very happy actually!), just let me know:

  • If I forgot some part of the use case, things to consider, ...
  • Where to start?

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature / enhancementNew feature or requestp2-nice-to-haveSvelteKit cannot be used by a small number of people, quality of life improvements, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions