“Using NextAuth, I prefetch the session on the index.tsx page with SSR and inject it into _app.tsx. However, when refreshing the browser on other URLs, the session from NextAuth is not injected.”
here is my code (SSR)
// index.tsx
export const getServerSideProps = (async (ctx: GetServerSidePropsContext) => {
const session = await getSession(ctx);
return { props: { session: session } };
}) satisfies GetServerSideProps<{ session: Session | null }>;
and
// _app.tsx
<SessionProvider session={session}>
<main className={cn(myFont.variable)}>
<CommonLayout>
<Component {...pageProps} />
</CommonLayout>
</main>
</SessionProvider>
To prefetch the session globally, using getInitialProps in _app.tsx would work, but it’s not recommended in Next.js, so I don’t want to use it.
I considered handling it in middleware, but since middleware doesn’t work on refresh, I don’t think that’s the solution.
How can I globally prefetch the session from NextAuth on the server and inject it, even on refresh?
I’m not currently employed. I’m a developer who wants to work in a company. Please, could you share how your company handles session management with NextAuth in a Next.js page router setup? I’m desperate to know. Please help…
최문길 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.