Fix crash from unhandled AuthApiError on stale refresh tokens
Build and Push Docker Images / build-portal (push) Successful in 1m53s Details
Build and Push Docker Images / build-infra (docker/db, monacousa-db) (push) Successful in 1m3s Details
Build and Push Docker Images / build-infra (docker/kong, monacousa-kong) (push) Successful in 21s Details
Build and Push Docker Images / build-infra (docker/migrate, monacousa-migrate) (push) Successful in 59s Details

getSession() throws AuthApiError when refresh token is invalid/expired
instead of returning null. This unhandled exception crashes the request
handler, causing 503s for all resources. Wrap getSession() and getUser()
in try-catch to handle gracefully and redirect to login.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Matt 2026-02-10 19:24:24 +01:00
parent 439d70c7e4
commit 0e04d016da
1 changed files with 18 additions and 9 deletions

View File

@ -48,21 +48,30 @@ const supabaseHandle: Handle = async ({ event, resolve }) => {
* Returns session, user, and member data
*/
event.locals.safeGetSession = async () => {
const {
data: { session }
} = await event.locals.supabase.auth.getSession();
let session;
try {
const { data } = await event.locals.supabase.auth.getSession();
session = data.session;
} catch (e) {
// Invalid/expired refresh token throws AuthApiError - handle gracefully
console.warn('Session retrieval error:', e instanceof Error ? e.message : e);
return { session: null, user: null, member: null };
}
if (!session) {
return { session: null, user: null, member: null };
}
// Validate the session by getting the user
const {
data: { user },
error: userError
} = await event.locals.supabase.auth.getUser();
if (userError || !user) {
let user;
try {
const { data, error: userError } = await event.locals.supabase.auth.getUser();
if (userError || !data.user) {
return { session: null, user: null, member: null };
}
user = data.user;
} catch (e) {
console.warn('User validation error:', e instanceof Error ? e.message : e);
return { session: null, user: null, member: null };
}