Script Valley
Next.js: Full-Stack React Applications
Authentication with NextAuth.jsLesson 5.4

How to access session data in Next.js Server and Client Components

auth() function in Server Components, useSession hook, SessionProvider, session object shape, user ID in session, callbacks for custom session data

Reading Session in Server Components

Call auth() directly in any Server Component or Route Handler โ€” no provider needed:

import { auth } from '@/auth'

export default async function Dashboard() {
  const session = await auth()

  if (!session?.user) redirect('/login')

  return <h1>Welcome, {session.user.name}</h1>
}

Session in Client Components

Wrap your app in SessionProvider (in a Client Component layout), then use useSession:

'use client'
import { SessionProvider } from 'next-auth/react'

export default function Providers({ children }: { children: React.ReactNode }) {
  return <SessionProvider>{children}</SessionProvider>
}
'use client'
import { useSession } from 'next-auth/react'

export default function UserMenu() {
  const { data: session, status } = useSession()
  if (status === 'loading') return <span>Loading...</span>
  if (!session) return <SignInButton />
  return <span>{session.user?.name}</span>
}

Adding User ID to Session

// In auth.ts callbacks:
callbacks: {
  session({ session, token }) {
    session.user.id = token.sub!  // sub is the user's ID in JWT
    return session
  },
}

By default, the session object only includes name, email, and image. Add the callbacks to include the user's ID or any custom fields.

Up next

How to protect routes with NextAuth.js middleware

Sign in to track progress

How to access session data in Next.js Server and Client Components โ€” Authentication with NextAuth.js โ€” Next.js: Full-Stack React Applications โ€” Script Valley โ€” Script Valley