Next.js Discord

Discord Forum

How to configure NextAuth shared session state for NextJS 14 app structure?

Unanswered
Birman posted this in #help-forum
Open in Discord
BirmanOP
NextAuth.js documentation says: to be able to use useSession first you'll need to expose the session context, <SessionProvider />, at the top level of your application:
and then provides example with pages/_app.jsx file:
import { SessionProvider } from "next-auth/react"

export default function App({
  Component,
  pageProps: { session, ...pageProps },
}) {
  return (
    <SessionProvider session={session}>
      <Component {...pageProps} />
    </SessionProvider>
  )
}

But I'm not using pages structure, because NextJs documentation says: For new applications, we recommend using the App Router.
My project structure looks like this:
.
├── README.md
├── next-env.d.ts
├── next.config.mjs
├── package-lock.json
├── package.json
├── postcss.config.js
├── public
│   ├── next.svg
│   └── vercel.svg
├── src
│   └── app
│       ├── api
│       │   └── auth
│       │       └── [...nextauth].ts
│       ├── components
│       │   └── Header.tsx
│       ├── favicon.ico
│       ├── globals.css
│       ├── layout.tsx
│       ├── page.tsx
│       ├── template.tsx
│       └── test-authentication
│           ├── private
│           │   └── page.tsx
│           └── public
│               └── page.tsx
├── tailwind.config.ts
└── tsconfig.json

Since I don't have _app.tsx file, where and how should I add <SessionProvider> wrapper?

1 Reply

BirmanOP
One way how to do it is to create a separate client component in components like so:
"use client";

import React from 'react';
import { SessionProvider } from "next-auth/react";

export default function AuthProvider({
  children,
}: {
  children: React.ReactNode;
}) {
  return <SessionProvider>{children}</SessionProvider>;
}

And then wrap root layout.tsx like so:
import "./globals.css";
import Header from "./components/Header";
import AuthProvider from "./components/AuthProvider";

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
        <body className={inter.className}>
        <AuthProvider>
            <Header />    
            {children}
        </AuthProvider>
    </body>
    </html>
  );
}