#ClientLoader behavior explanation

1 messages · Page 1 of 1 (latest)

flint crow
#

Versions:
"@remix-run/node": "^2.12.0",
"@remix-run/react": "^2.12.0",

Hey folks, I have a bit of weird behavior happening with my clientLoaders in Remix SPA. I have some context that I'm setting with a provider at the top level parent component. This provider helps set authentication headers on all of the child components' API calls. My issue is that the authentication headers are sometimes not set correctly when making a request from the clientLoader.

I'm trying to understand something as the docs for both Remix and React Router v7 don't feel complete for clientLoader. Does anyone understand/can explain the sequence of operations for for the client loader? Would the parent context be set prior to client loaders running the first time or should I not expect that to be the case?

I'll share a little more context here. The provider mutates an API client instance, setting the auth header, so any later use of the api instance should have the authentication header set to the proper session token.

My clientLoader then looks like this:

export const clientLoader = async () => {
  return {
    shop: await api.shopifyShop.findFirst({
      select: {
        currency: true,
        bundleCount: true,
      },
    }),
  };
};

I tried the same API call within the loader's component using a hook with the same behavior and it works.

So to summarize, clientLoader returns a 403 and the hook returns a 200.

mortal bear
#

clientLoader executes outside of React. Since you're mutating a global api instance, then that could potentially introduce a race condition, depending on how you have your client loaders set up. If you don't have any server loaders, then they are implicitly hydrate = true, which means they'll run before any routes render (including root). If the component that's mutating the api is doing so in your entry.client.tsx, then one solution could be to block rendering of any children until that mutation is complete, which would block rendering of the <RemixBrowser> component entirely. This has the downside of introducing more latency / waterfalls into your client rendering, unfortunately.

flint crow
#

Is that still the fact with Remix SPA?

#

That sounds like SSR behavior to me

mortal bear
#

Yes, the browser-side React Router components behave the same whether ssr is enabled or not. What that determines is the default implementation of the route module's loader, and how the initial document request behaves.