kit: Setup each page - init hook, `export const blocking`, etc.
Describe the problem
For i18n or similar subsystems, we should make initialization before any language things are needed, and for such initialization, we usually use a session (user language) and information from the HTTP request. Before the new routing system was introduced, we were using the root __layout.svelte to do it, it’s working well for SSR and CSR time. I should mention that what i18n should be inited on the server side and init on the client side as well (or state should be send as is).
After migration to new routing, we lose one “transitional” place to init such thing because +layout.js
can be called after +page.js
, and you must do await parent()
in each page to avoid such race condition.
For server-side only init, we have a good place it’s handle
in hooks.js
with event.locals
it’s an excellent way to init server only things like DB connection, but for things what should be a transition from SSR to CSR we have no place.
I also have a similar issue for i18n implementation project what I use https://github.com/cibernox/svelte-intl-precompile/issues/55
Describe the proposed solution
Maybe it’s possible to do it more straightforwardly, but at least we need a global hook for what will be called on SSR and on CSR, after +layout.server.js
but before +layout.js
and +page.js
.
Alternatives considered
No response
Importance
would make my life easier
Additional Information
No response
About this issue
- Original URL
- State: open
- Created 2 years ago
- Reactions: 6
- Comments: 34 (30 by maintainers)
Commits related to this issue
- await parent() in page load functions until client hooks init arrives https://github.com/sveltejs/kit/issues/6183 — committed to livingtongues/living-dictionaries by jacob-8 2 years ago
Here’s what i’ve been experimenting with today:
lang.ts
hooks.client.ts
hooks.server.ts
Is this a valid approach?
My proposal would be an exported
init
orinitialize
(can’t think of a better name) function inhooks.client.js
that gets called (and awaited) right after theinit
function in https://github.com/sveltejs/kit/blob/177a5a9f8219f3f9633d8f8dc879f8472f74d6a2/packages/kit/src/runtime/client/start.js#L28Maybe the returned value could be the equivalent of
locals
in the client-sideload
functions or merged withdata
.If I understand you correctly, it could work today for you, too, but you’d have to do
await parent()
in each layout/page, which is cumbersome. I had this concern, too. My idea was to introduceexport const blocks = <boolean>
to+layout.js
(and possibly tolayout.server.js
) so you have to write it in one place only for situations like this.Another thing coming up from a discussion: When doing this in the root layout and the setup depends on things that are causing the load function to rerun, the setup code might be rerun when you don’t want that. #6294 could also help with that.