NextAuth.js SessionProvider: Setup & Usage Guide

Answered using AI by Vibe Coding

Code Question:

what is SessionProvider?how to use

Code Solution:

SessionProvider is a React Context provider that comes from NextAuth.js (now called Auth.js).
It wraps your entire React/Next.js app (or a part of it) and makes the current user’s session object available to every component that needs it, without prop-drilling.


1. What it does

  • Holds the current session (user, token, etc.) in React Context.
  • Automatically refreshes the session when it expires.
  • Exposes the useSession() hook so any component can read the session.

2. How to use it (step-by-step)

a. Install NextAuth.js

npm i next-auth

b. Create the API route

File: pages/api/auth/[...nextauth].js (or .ts)

import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";

export default NextAuth({
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID,
      clientSecret: process.env.GITHUB_SECRET,
    }),
  ],
});

c. Wrap your app with SessionProvider

In Next.js 13+ (App Router)
File: app/providers.tsx

"use client"; // must be client component

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

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

Then import it in your root layout:
File: app/layout.tsx

import AuthProvider from "./providers";

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <AuthProvider>{children}</AuthProvider>
      </body>
    </html>
  );
}

In Next.js 12 or Pages Router
File: pages/_app.tsx

import { SessionProvider } from "next-auth/react";
import type { AppProps } from "next/app";

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

d. Use the session anywhere

"use client"; // or plain component in pages router

import { useSession } from "next-auth/react";

export default function UserCard() {
  const { data: session, status } = useSession();

  if (status === "loading") return <p>Loading…</p>;
  if (status === "unauthenticated") return <p>Not signed in</p>;

  return (
    <div>
      <p>Signed in as {session.user?.email}</p>
    </div>
  );
}

3. Key points

  • Only components under the SessionProvider can call useSession().
  • In the App Router, mark the provider file with "use client" because Context only works on the client.
  • You can pass session={pageProps.session} in Pages Router to avoid an extra fetch on first load (hydration optimization).

That’s all—SessionProvider is just the glue that makes NextAuth.js session data globally available to your React tree.