Leave Localhost logoLeave LocalhostDocs
Authentication

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

  1. 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.
  2. Validation: For subsequent requests, the client sends the cookie. The Better Auth middleware validates the session against the database.
  3. 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.

On this page