T
TanStack6mo ago
constant-blue

beforeLoad call frequency

Can someone refer to me some documentation about when and how many times does beforeLoad runs, does it run on every route match or more than that. it seems my root route beforeLoad function gets called twice on every route match and even more. could someone help here on how and when does it get called?
9 Replies
conscious-sapphire
conscious-sapphire6mo ago
once per navigation could occur twice if you have intent preloading enabled
constant-blue
constant-blueOP6mo ago
@Manuel Schiller , so before my understanding was that since we have nested routes and root route is always mounted, does the beforeLoad / loader for root route need to run on every navigation? could you help me understand this, as I have been using react-router for sometime, is this behaviour different from react router?
conscious-sapphire
conscious-sapphire6mo ago
yes root's beforeLoad runs for every navigation
constant-blue
constant-blueOP6mo ago
could you help me understand if there is any benefit of running root route's beforeLoad / loader hooks on every navigations. basically I wanna understand the reasoning behind this way of working, since its different from react router v7 where its not the case. thanks for prompt reply. refer to me some documentation on this if available.
wise-white
wise-white6mo ago
+1 would love to understand the rationale of this as it gave me a few headaches in the past and seems a common friction point that makes the use of a cache almost necessary when using beforeLoad for auth.
constant-blue
constant-blueOP6mo ago
@Tanner Linsley could you help us with this query, this would make things more clear for all of us
ambitious-aqua
ambitious-aqua4mo ago
I also want to comprehend.
conscious-sapphire
conscious-sapphire4mo ago
what exactly?
generous-apricot
generous-apricot4mo ago
In particular in the case of auth this is exactly what you want. If the beforeLoad func that handles your auth is automatically cached, subroute navigations might still work, even when auth state changes (e.g. because the user logged out in another tab). See this discussion for sveltekit about this topic: https://github.com/sveltejs/kit/issues/6315 beforeLoad is, as the docs state a middleware. It is exactly intended to run on every request. If you do not want to check auth on every request, than this is a decision that you need to make.
GitHub
Attack vector arising from naive developer use of the `+layout.serv...
Describe the bug tldr; The existence of the +layout.server.js tree will lead folks to put logic there rather than in +page.server.js. Because SvelteKit decides on the client what to fetch from the ...

Did you find this page helpful?