Read the current session
Server-rendered pages and API handlers need to identify the signed-in user from incoming request headers.
Better Auth · Pipe
Better Auth uses cookie-based sessions: the server validates the session cookie on requests and returns the associated user when valid. Session expiration, freshness, storage, and management APIs are configurable.
Better Auth uses a cookie-based session: the browser sends the session cookie with each request, and the server verifies it before returning the associated user data. Session lifetime and renewal behavior are configurable, while session APIs support reading, listing, revoking, and updating sessions.
betterAuth({ session: { expiresIn, updateAge } })
auth.api.getSession({ headers })| Name | Type | Description |
|---|---|---|
options | BetterAuthOptions | Configuration object passed to betterAuth; its session options include expiresIn and updateAge. |
headers | Headers | Request headers containing the session cookie when calling auth.api.getSession. |
getSession returns the current active session and its user data when the session is valid; otherwise no valid session is returned.
import { betterAuth } from "better-auth";
export const auth = betterAuth({
session: {
expiresIn: 60 * 60 * 24 * 7,
updateAge: 60 * 60 * 24,
},
});
const session = await auth.api.getSession({
headers: request.headers,
});Creates a Better Auth instance with a seven-day session lifetime and a one-day renewal threshold, then retrieves the active session from request headers.
Server-rendered pages and API handlers need to identify the signed-in user from incoming request headers.
Applications need automatic expiration and periodic renewal without forcing users to sign in repeatedly.
Security settings or account management require ending one or more active logins.
Better Auth stores the session in a cookie and sends it to the server on each request. The server verifies the session and returns user data only when the session is valid.
Follow-up: How can session lookups avoid the primary database? Configure a secondary storage such as Redis; Better Auth checks it before falling back to the database.
The session expires after seven days by default. The expiresIn setting controls the lifetime, while updateAge determines when using the session causes its expiration to be extended.
Follow-up: What happens when secondary storage is configured? Sessions are stored there instead of the database by default, unless storeSessionInDatabase is enabled.
getSession retrieves the active session, useSession provides reactive access, and revokeSession ends a session using its token. updateSession can change configured additional session fields.
Follow-up: How would you support multiple active devices? Use listSessions to obtain the user's active sessions and revoke individual sessions by token.
getSessionuseSessionlistSessionsrevokeSessionupdateSessionexpiresInupdateAgefreshAge