From c83349200cbc7d9c3dbc052071b14dcfdcd6ecaa Mon Sep 17 00:00:00 2001 From: Theodore Li Date: Wed, 8 Apr 2026 16:07:30 -0700 Subject: [PATCH] fix(error): catch socket auth error as 4xx (#4059) * fix(error): catch socket auth error as 4xx * Switch to type guard --------- Co-authored-by: Theodore Li --- apps/sim/app/api/auth/socket-token/route.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/apps/sim/app/api/auth/socket-token/route.ts b/apps/sim/app/api/auth/socket-token/route.ts index 2a6965ee06..810f149b8b 100644 --- a/apps/sim/app/api/auth/socket-token/route.ts +++ b/apps/sim/app/api/auth/socket-token/route.ts @@ -23,6 +23,18 @@ export async function POST() { return NextResponse.json({ token: response.token }) } catch (error) { + // better-auth's sessionMiddleware throws APIError("UNAUTHORIZED") with no message + // when the session is missing/expired — surface this as a 401, not a 500. + if ( + error instanceof Error && + ('statusCode' in error || 'status' in error) && + ((error as Record).statusCode === 401 || + (error as Record).status === 'UNAUTHORIZED') + ) { + logger.warn('Socket token request with invalid/expired session') + return NextResponse.json({ error: 'Authentication required' }, { status: 401 }) + } + logger.error('Failed to generate socket token', { error: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined,