Sessions
Better Auth handles session management automatically, creating and managing secure sessions when a user authenticates.
Better Auth handles session management automatically, creating and managing secure sessions when a user authenticates.
How Sessions Work
- Creation: Upon successful login, Better Auth creates a session record in the database and sets a secure, HTTP-only cookie on the client's browser.
- Validation: For subsequent requests, the client sends the cookie. The Better Auth middleware validates the session against the database.
- Expiration: Sessions have a configurable expiration time. They can also be invalidated manually (e.g., when a user logs out).
Accessing Session Data
Client-Side (React/Next.js)
You can access the current session and user data using the hooks provided by the Better Auth client in your frontend components.
import { useSession } from "@/lib/auth/client"; // Adjust import path
export function UserProfile() {
const { data: session, isPending } = useSession();
if (isPending) return <div>Loading...</div>;
if (!session) return <div>Not authenticated</div>;
return <div>Welcome, {session.user.email}</div>;
}Server-Side (Convex)
Within your Convex queries and mutations, you verify the session to ensure the request is authorized. The @convex-dev/better-auth integration provides utilities for this.
import { query } from "./_generated/server";
import { getAuthUserId } from "@convex-dev/auth/server";
export const getMyData = query({
args: {},
handler: async (ctx) => {
const userId = await getAuthUserId(ctx);
if (userId === null) {
throw new Error("Not authenticated");
}
// Fetch user-specific data using userId
return await ctx.db.query("myData").withIndex("by_user", q => q.eq("userId", userId)).collect();
},
});Session Invalidation (Logout)
When a user signs out, Better Auth destroys the session in the database and clears the client-side cookie, ensuring that the session cannot be reused.
Microsoft OAuth
Microsoft OAuth allows users to sign in using their Microsoft Entra ID (formerly Azure AD) accounts. This is particularly useful for B2B applications where users sign in with their corporate accounts.
Multi-Factor Authentication (MFA)
Multi-Factor Authentication (MFA) adds an extra layer of security by requiring users to provide two forms of verification before accessing their accounts. The starter supports Time-Based One-Time Passwords (TOTP) natively using Better Auth.