From 53fca6823a8ac35c03bea1cfb8b97f7613dcc9d0 Mon Sep 17 00:00:00 2001 From: ephraimduncan Date: Mon, 26 Jan 2026 11:23:41 +0000 Subject: [PATCH 1/2] fix: memoize session to prevent race condition on dashboard Wrap getSession() with React's cache() and use it in TRPC context to ensure layout and TRPC share the same session within a request. Fixes sporadic UNAUTHORIZED errors when cookie cache expires mid-request. --- packages/api/trpc.ts | 4 ++-- packages/auth/server.ts | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/api/trpc.ts b/packages/api/trpc.ts index d49791e..feac7fa 100644 --- a/packages/api/trpc.ts +++ b/packages/api/trpc.ts @@ -2,11 +2,11 @@ import { initTRPC, TRPCError } from '@trpc/server'; import superjson from 'superjson'; import { ZodError } from 'zod'; -import { auth } from '@formbase/auth'; +import { getSession } from '@formbase/auth/server'; import { db } from '@formbase/db'; export const createTRPCContext = async (opts: { headers: Headers }) => { - const session = await auth.api.getSession({ headers: opts.headers }); + const session = await getSession(); const user = session?.user ?? null; return { diff --git a/packages/auth/server.ts b/packages/auth/server.ts index a6413dd..d143f0b 100644 --- a/packages/auth/server.ts +++ b/packages/auth/server.ts @@ -1,10 +1,11 @@ +import { cache } from 'react'; import { headers } from 'next/headers'; import { auth } from './index'; -export async function getSession() { +export const getSession = cache(async () => { return auth.api.getSession({ headers: await headers() }); -} +}); export async function requireAuth() { const session = await getSession(); From c207125f4242fe1da67fa08d3e72219e68278a5c Mon Sep 17 00:00:00 2001 From: ephraimduncan Date: Mon, 26 Jan 2026 11:27:28 +0000 Subject: [PATCH 2/2] fix: handle React.cache unavailable in test environment --- packages/auth/server.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/packages/auth/server.ts b/packages/auth/server.ts index d143f0b..ce3224a 100644 --- a/packages/auth/server.ts +++ b/packages/auth/server.ts @@ -1,8 +1,13 @@ -import { cache } from 'react'; +import * as React from 'react'; import { headers } from 'next/headers'; import { auth } from './index'; +const cache = + typeof React.cache === 'function' + ? React.cache + : unknown>(fn: T) => fn; + export const getSession = cache(async () => { return auth.api.getSession({ headers: await headers() }); });