Skip to content

Session Cookie Caching issue #73

@MikeyZhang75

Description

@MikeyZhang75

Description

I've enabled session cookie caching in Better Auth configuration, which according to the documentation should provide near-instant (0-1ms) response times from the /api/auth/get-session endpoint by reading from the cached cookie instead of making a database call. However, I'm consistently seeing 340-360ms response times.

Current Behavior

  • Session fetch takes 340-360ms on every request
  • The /api/auth/get-session endpoint appears to be making a full round-trip each time
  • No apparent caching is occurring despite configuration

Expected Behavior

  • With cookieCache enabled, subsequent session fetches should take 0-1ms
  • The session should be read directly from the cookie without hitting the endpoint

Configuration

Auth Configuration (packages/database/lib/auth.ts):

import { convexAdapter } from "@convex-dev/better-auth";
import { convex } from "@convex-dev/better-auth/plugins";
import { requireEnv } from "@convex-dev/better-auth/utils";
import type { GenericCtx } from "@repo/database/convex/_generated/server";
import { betterAuthComponent } from "@repo/database/convex/auth";
import { betterAuth } from "better-auth";
import { admin } from "better-auth/plugins";

const siteUrl = requireEnv("SITE_URL");

export const createAuth = (ctx: GenericCtx) =>
	// Configure your Better Auth instance here
	betterAuth({
		// All auth requests will be proxied through your next.js server
		baseURL: siteUrl,
		database: convexAdapter(ctx, betterAuthComponent),

		// Simple non-verified email/password to get started
		emailAndPassword: {
			enabled: true,
			requireEmailVerification: false,
		},
		plugins: [
			// The Convex plugin is required
			convex(),
			admin(),
		],
		session: {
			cookieCache: {
				enabled: true,
				maxAge: 5 * 60, // Cache duration in seconds
			},
		},
	});

Middleware Implementation:

import { betterFetch } from "@better-fetch/fetch";
import type { createAuth } from "@repo/database/lib/auth";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

type Session = ReturnType<typeof createAuth>["$Infer"]["Session"];
const getSession = async (request: NextRequest) => {
	const { data: session } = await betterFetch<Session>(
		"/api/auth/get-session",
		{
			baseURL: request.nextUrl.origin,
			headers: {
				cookie: request.headers.get("cookie") ?? "",
				origin: request.nextUrl.origin,
			},
		},
	);
	return session;
};

// Public authentication routes
const authRoutes = ["/auth"];

export default async function middleware(request: NextRequest) {
	console.log("Middleware started");
	const { pathname } = request.nextUrl;

	const startTime = Date.now();

	// Get the session cookie using Better Auth's helper
	const session = await getSession(request);

	const endTime = Date.now();
	console.log("Session fetch time (ms):", endTime - startTime);

	// Check if this is an auth route
	const isAuthRoute = authRoutes.some((route) => pathname.startsWith(route));

	// If on auth route and no session, allow access
	if (isAuthRoute && !session) {
		return NextResponse.next();
	}

	// If on auth route but has session, redirect to home
	if (isAuthRoute && session) {
		return NextResponse.redirect(new URL("/", request.url));
	}

	// If not on auth route and no session, redirect to auth
	if (!isAuthRoute && !session) {
		const authUrl = new URL("/auth", request.url);
		authUrl.searchParams.set("redirect", pathname);
		return NextResponse.redirect(authUrl);
	}

	// Has session and accessing protected route, allow
	return NextResponse.next();
}

export const config = {
	// Run middleware on all routes except static assets and api routes
	matcher: ["/((?!.*\\..*|_next|api/auth).*)", "/"],
};

Console Output

Middleware started
GET /api/auth/get-session 200 in 361ms
Session fetch time (ms): 366
GET /test 200 in 93ms
Middleware started
GET /api/auth/get-session 200 in 340ms
Session fetch time (ms): 347
GET / 200 in 40ms

Environment

  • Next.js with App Router
  • Better Auth with Convex integration
  • Running in development mode

Questions

  1. Am I using the wrong method to fetch the session in middleware?
  2. Should I be using a different Better Auth helper that reads from the cookie cache directly?
  3. Is there additional configuration needed to enable cookie caching?

Any guidance on proper session cookie cache implementation would be greatly appreciated!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions