Preloading route data with context access
I want to preload data for a Home route nested within an authenticated web app. I am doing this by passing a preload function like so:
However, in my preloadHome function I need to access some values from a context provider, like for example an auth API key. But the preloadHome function can't access any context providers that I have since they aren't in the rendering context.
What should I do in this situation?
7 Replies
To add some color...
This happens when I reload my web app on the home endpoint which is protected by a route guard for auth. The preload runs immediately, before I've had the chance to set up my API client with my auth key. In my component tree this isn't possible since the route guard prevents renders until auth has been established / confirmed. But since the preload runs regardless of this, it runs before my auth flow has finished, and errors. I am not sure what the best practice is for architecting this in a better way such that my Home page preloads data as soon as its able to, which is earlier than when Home is rendered but later than when the route is initially matched
You can’t access context in preload functions. They are called outside of the app.
But cookies will be included in the request.
So if you fetch with credentials:"include" you can add tokens / api keys that way.
Ah ok. Any other architectures that I should consider? Should I make my store with auth info a singleton export outside of context so that my preload function can import that and read it directly? Or is that bad for some reasons I'm unaware of?
That won’t work (also with signal), because they will get initialised on the server and then again on the client with a different ref. This can lead to hydration issues.
Are you intending to use a server or are you creating a pure SPA with an external API?
If you put the context outside of
Router
i think you actually can access those contexts in preload
we made a change a while ago so that preloads ran within the router's owner
, which includes contextsWell depends:
e.g. if the preload functions uses "use server" it cannot access the client's context, right?
That's why I prefer cookies which are included in requests from the client and can be accessed on the server.
So the answer would be it depends on how
preloadHome
is implemented.Yeah, but making the preload function a server function kinda defeats the point