Search code examples
next.jsnext-auth

Why is session undefined inside _app component


I am trying to conditionally include a <Layout> component based on whether a user is logged in or not. Naturally, my first instinct is to do this inside the _app component, since the Layout applies to every page.

However, for some reason, it seems like session is undefined in the _app component, no matter what...
I guess by the time _app renders, the SessionProvider is not initialized? I don't really understand why that would be, or whether I'm doing something wrong.

import { type AppType } from "next/app";
import { type Session } from "next-auth";
import { SessionProvider } from "next-auth/react";
import { api } from "../utils/api";
import "../styles/globals.css";
import Layout from "../components/layout";

const MyApp: AppType<{ session: Session | null }> = ({
  Component,
  pageProps: { session, ...pageProps },
}) => {
  return (
    <SessionProvider session={session}>
      {/* if logged in, include layout component */}
      {session && (
        <Layout>
          A
          <Component {...pageProps} />
        </Layout>
      )}
      {/* if not logged in, don't include layout component */}
      {!session && (
        <>
          <Component {...pageProps} />
          {console.log(session)}
        </>
      )}
    </SessionProvider>
  );
};

export default api.withTRPC(MyApp);

Solution

  • This is not how to check the session.

    What you have to do is to access the session from your Layout :

    import { useSession } from "next-auth/react";
    const Layout = (props) => {
      const { status } = useSession();
    //...
    }
    

    Then before returning the layout jsx you check if the user is not authenticated so you don't return the layout but only props.children :

    if(status !== "authenticated"){
    return <>{props.children}</>
    }