Scenario: I want to use clientLoader for "snappier" navigation in a #reactrouter
application, but still need to check authentication at the route. If
authentication is persisted by an HTTP-only cookie, then we can't check it from
Request in a clientLoader.
So we'll just call serverLoader from clientLoader, and trust that
react-router will take care to reduce the number of fetches per-page-load.
export async function loader({ request }: Route.LoaderArgs) {
const cookie = request.headers.get("cookie")
const { isAuthenticated } = await checkAuthentication(request) // checks a cookie
if (!isAuthenticated) {
throw Error("User is not authenticated")
}
// ...
}
// we can call the server-side loader like so.
export async function clientLoader({ serverLoader }: Route.ClientLoaderArgs) {
return serverLoader()
}
P.S. It's best-practice to check authentication at every route, rather than rely on a wrapper route/layout.
P.S.P.S
Per react-router documentation, you don't actually need to call
serverLoader unless you intend to fetch additional data beyond what loader
is already doing, since the framework will automatically dispatch a fetch to the
loader on client navigation.
When server rendering, loader is used for both initial page loads and client
navigations. Client navigations call the loader through an automatic fetch by
React Router from the browser to your server.