diff --git a/ui/litellm-dashboard/src/app/dashboard/hooks/useAuthorized.ts b/ui/litellm-dashboard/src/app/dashboard/hooks/useAuthorized.ts index 9d436d0566f..74c0476f199 100644 --- a/ui/litellm-dashboard/src/app/dashboard/hooks/useAuthorized.ts +++ b/ui/litellm-dashboard/src/app/dashboard/hooks/useAuthorized.ts @@ -1,24 +1,41 @@ "use client"; -import { getCookie } from "@/utils/cookieUtils"; +import { useEffect, useMemo } from "react"; +import { getCookie, clearTokenCookies } from "@/utils/cookieUtils"; import { useRouter } from "next/navigation"; import { jwtDecode } from "jwt-decode"; const useAuthorized = () => { - const token = getCookie("token"); const router = useRouter(); - if (!token) { - router.replace("/sso/key/generate"); - } + const token = typeof document !== "undefined" ? getCookie("token") : null; - const decoded = jwtDecode(token as string) as { [key: string]: any }; - const accessToken = decoded.key; - const userId = decoded.user_id; - const userRole = decoded.user_role; - const premiumUser = decoded.premium_user; + // Redirect after mount if missing/invalid token + useEffect(() => { + if (!token) { + router.replace("/sso/key/generate"); + } + }, [token, router]); - return { accessToken, userId, userRole, premiumUser }; + // Decode safely + const decoded = useMemo(() => { + if (!token) return null; + try { + return jwtDecode(token) as Record; + } catch { + // Bad token in cookie — clear and bounce + clearTokenCookies(); + router.replace("/sso/key/generate"); + return null; + } + }, [token, router]); + + return { + accessToken: decoded?.key ?? null, + userId: decoded?.user_id ?? null, + userRole: decoded?.user_role ?? null, + premiumUser: decoded?.premium_user ?? null, + }; }; export default useAuthorized; diff --git a/ui/litellm-dashboard/src/app/layout.tsx b/ui/litellm-dashboard/src/app/layout.tsx index 8a37d0fa1bf..9b6c027a56c 100644 --- a/ui/litellm-dashboard/src/app/layout.tsx +++ b/ui/litellm-dashboard/src/app/layout.tsx @@ -18,9 +18,12 @@ export default function RootLayout({ }>) { return ( - - {children} - + + + + {children} + + ); } diff --git a/ui/litellm-dashboard/src/utils/cookieUtils.ts b/ui/litellm-dashboard/src/utils/cookieUtils.ts index 2cc9ef61ebd..e477a9f77e0 100644 --- a/ui/litellm-dashboard/src/utils/cookieUtils.ts +++ b/ui/litellm-dashboard/src/utils/cookieUtils.ts @@ -37,6 +37,7 @@ export function clearTokenCookies() { * @returns The cookie value or null if not found */ export function getCookie(name: string) { + if (typeof document === "undefined") return null; const cookieValue = document.cookie.split("; ").find((row) => row.startsWith(name + "=")); return cookieValue ? cookieValue.split("=")[1] : null; }