From de05ca2ecf004cab5a4bdbc6ff8a3ffd5f06710c Mon Sep 17 00:00:00 2001 From: kyuuseiryuu Date: Mon, 16 Mar 2026 12:51:39 +0900 Subject: [PATCH] feat: fallback to auto-login on token failure and improve redirect logic - In `useAuthHeaders`, import `useAutoLogin` and trigger login if `getAccessToken` returns a falsy value. This handles edge cases where the token is expired or missing during an API call. - In `useAutoLogin`, set the default redirect URL to `window.location.pathname` to ensure users return to the page they were on before logging in. --- src/hooks/useAuthHeaders.ts | 6 ++++++ src/hooks/useAutoLogin.ts | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/src/hooks/useAuthHeaders.ts b/src/hooks/useAuthHeaders.ts index 91982e7..f54ad95 100644 --- a/src/hooks/useAuthHeaders.ts +++ b/src/hooks/useAuthHeaders.ts @@ -1,13 +1,19 @@ import { useLogto } from "@logto/react" import { useEffect, useState } from "react"; import { LOGTO_RESOURCE } from "../utils/constants"; +import useAutoLogin from "./useAutoLogin"; export const useAuthHeaders = (): HeadersInit => { const { isAuthenticated, getAccessToken } = useLogto(); + const { login } = useAutoLogin(); const [headers, setHeaders] = useState({}); useEffect(() => { if (isAuthenticated) { getAccessToken(LOGTO_RESOURCE).then(token => { + if (!token) { + login(); + return; + } setHeaders({ Authorization: `Bearer ${token}` }) }); } diff --git a/src/hooks/useAutoLogin.ts b/src/hooks/useAutoLogin.ts index eb1fc39..5c4f780 100644 --- a/src/hooks/useAutoLogin.ts +++ b/src/hooks/useAutoLogin.ts @@ -3,7 +3,7 @@ import { useNavigate } from "react-router"; const useAutoLogin = () => { const navigate = useNavigate(); - const login = useCallback((redirect?: string) => { + const login = useCallback((redirect = window.location.pathname) => { if (redirect) { sessionStorage.setItem('redirect', redirect); }