Server component session access
Read the current user or session in server-rendered application code.
Auth.js · Function
Auth.js’s Next.js auth function is a universal server-side authentication API. Export it from NextAuth configuration, call it to read the session, or use it to wrap handlers and inspect request authentication.
In a Next.js application, NextAuth returns an auth function from the central configuration. Calling it without arguments reads the current session, while wrapping a route handler exposes the session as req.auth; the same universal method can be used across middleware, server components, route handlers, and API routes.
const { auth } = NextAuth(config)
const session = await auth()
export const GET = auth(handler)Session or null when called without arguments; wrapped request handlers receive req.auth containing the authenticated user or token, if any.
import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"
export const { handlers, auth } = NextAuth({
providers: [GitHub],
})
export default async function Page() {
const session = await auth()
return <p>{session ? `Signed in as ${session.user?.name}` : "Not signed in"}</p>
}Initialize Auth.js in the root configuration and call the exported auth function in a server component.
Read the current user or session in server-rendered application code.
Protect or authenticate an app route, Edge route, or Node API route.
Apply authentication-aware behavior in Next.js middleware.
auth is the universal Next.js method returned by NextAuth. It can be used in middleware, server components, route handlers, and Edge or Node.js API routes to access authentication state.
Follow-up: How can an API route use it? Wrap the handler with auth, then read the authenticated value from req.auth.
Create an auth.ts configuration file, initialize NextAuth there, and export auth with the other returned helpers. Server-side code can then call await auth() to obtain the session.
Follow-up: Why centralize this configuration? The exported function is reusable across the supported Next.js execution contexts instead of requiring separate session APIs.
For a route handler, auth can wrap the handler function. The request receives an auth property containing the authenticated user or token when available, or null otherwise.
Follow-up: How is general authorization configured? Auth.js performs authentication through the callbacks.authorized callback.
NextAuthhandlerssignInsignOutcallbacks.authorizedSession