Next.js Discord

Discord Forum

AppRouter & layout.tsx

Unanswered
Rainbow trout posted this in #help-forum
Open in Discord
Avatar
Rainbow troutOP
Hi, I'm using a 3rd party library (UI components) thats requires to set some ClientContext on top of that it sets/reads stuff from document. & body i believe and reads localstorage.
I created a provider.tsx file for that and set "use client"; but even then it complained about document not being acessable so i did a simple:

"use client";
export const Providers = ({
  children,
  session,
}: React.PropsWithChildren<{ session: Session }>) => {
  const [isClient, setIsClient] = useState(false);
  useEffect(() => {
    if (typeof window !== "undefined") {
      setIsClient(true);
    }
  }, []);

  if (!isClient) {
    return <Loader size="large" />; // I know this is ppointless :) 
  } else
    return (
      <ThirdPartyContextWrapper>
        <ThirdPartyLayer>
          <SessionProvider session={session}>
            <TopBar />
            {children}
          </SessionProvider>
        </ThirdPartyLayer>
      </ThirdPartyContextWrapper>
    );
};


Now, I can Wrap every single route/page with this Provider that gives me what I need. Without this context basically every single UI component available behaves like madness.
But surely ideally I'd want to shove this into my layout.tsx file? Or is it just common practice to for instance re-declare the SessionProvider (next-auth) in every page/route?

2 Replies

Avatar
Rainbow troutOP
Just feels odd to have to redeclare this on every page/route:
export default async function AnotherRoute() {
  const session = await auth();

  if (session)
    return (
      <Providers session={session}>
        AnotherRoute
      </Providers>
    );
  if (!session) return <AppLoader />;
}
Avatar
Rainbow troutOP
This would normally be solved in _app.tsx I suppose but i thought layout was more or less the new version of that