Load the signed-in user
Server-rendered pages
Better Auth · Module
auth.api.getSession retrieves the current server-side session by receiving the incoming request headers. Use its result to access session data or reject unauthenticated requests.
Call the server auth instance's getSession endpoint with the request headers. Better Auth uses those headers to identify the requester and returns the session data when valid; otherwise, treat the result as unauthenticated.
await auth.api.getSession({ headers: await headers() })| Name | Type | Description |
|---|---|---|
headers | Headers or compatible request-headers object | Incoming request headers used to identify the user's session. |
The current session object when the request is authenticated; otherwise, no session (null/absent result).
import { headers } from "next/headers";
import { auth } from "./auth";
export async function getCurrentUser() {
const session = await auth.api.getSession({
headers: await headers(),
});
return session?.user ?? null;
}Pass the incoming request headers so Better Auth can resolve the current session; a missing session produces null.
Server-rendered pages
Protected API routes
Server actions
Call auth.api.getSession({ headers: await headers() }) on the server. The headers carry the user's session token, and the returned session can be used to access session data.
Follow-up: How would you protect an API route? Pass that route's incoming headers, then return an unauthorized response when the result is absent.
The server API receives endpoint arguments in an object. For this method, the relevant property is headers, containing the request headers; the API object exposes Better Auth endpoints.
Follow-up: How are body and query arguments represented for other endpoints? They are passed under body and query, respectively, while headers remain under headers.
A missing session should be handled as an unauthenticated request. Check the result before using user data, and reject the request rather than processing protected work.
Follow-up: How can a server endpoint return the underlying HTTP response details? Use the endpoint's asResponse option when that response form is required.
auth.apiauth.api.signInEmailgetSessionCookiereturnHeadersasResponse