Read authenticated server state
Server-rendered pages and server components need the signed-in user's identity or metadata.
Auth.js · Pipe
Retrieve the authenticated user's session in server or client code. Auth.js uses auth() on the server and useSession() on the client, with SessionProvider required for client-side access.
Auth.js exposes the current session through server-side auth() or client-side useSession(). On the client, useSession() must be rendered beneath SessionProvider; on the server, auth() returns the session object when the user is authenticated and a falsy value otherwise.
const session = await auth()
const { data: session } = useSession()The current session object when an authenticated session exists; otherwise null or another falsy result, depending on the integration.
import NextAuth from "next-auth"
export const { auth } = NextAuth({
providers: [],
})
export async function getCurrentUser() {
const session = await auth()
return session?.user ?? null
}Call the exported auth function on the server and use the returned session when it exists.
Server-rendered pages and server components need the signed-in user's identity or metadata.
Interactive client components need to update their UI based on sign-in state.
A route or page must decide whether to continue, redirect, or reject an unauthenticated request.
On the server, use the auth function returned from NextAuth and exported from the Auth.js configuration. It provides the current session, which can then be checked before rendering protected content.
Follow-up: How would you read it in a client component? Use useSession(), but ensure SessionProvider wraps the component tree.
useSession() is the client-side session hook. It should be used beneath SessionProvider, which supplies session state to descendant components.
Follow-up: What should a protected client view do while the session is unresolved? Handle the loading state before deciding whether to render authenticated or unauthenticated content.
The session endpoint returns the user's session when one exists and null otherwise. Session checks can therefore distinguish an authenticated request from one without an active session.
Follow-up: How can the result be used for route protection? Redirect or return an unauthenticated response when no valid session is present.
auth()useSession()SessionProviderNextAuth()event.sharedMap.get("session")