Skip to content

Commit 232ea70

Browse files
committed
add an iterceptor to auto logout user if the session is expired
1 parent 34aed21 commit 232ea70

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

hooks/useFetchInterceptor.tsx

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import { useEffect } from 'react';
2+
import { signOut } from 'next-auth/react';
3+
4+
const useFetchInterceptor = () => {
5+
useEffect(() => {
6+
const handleResponse = (response: Response) => {
7+
if (response.status === 401) {
8+
const currentUrl = window.location.href;
9+
signOut({ callbackUrl: `/api/auth/signin?error=SessionRequired&callbackUrl=${encodeURIComponent(currentUrl)}` });
10+
}
11+
return response;
12+
};
13+
14+
const originalFetch = global.fetch.bind(global);
15+
16+
global.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
17+
const response = await originalFetch(input, init);
18+
return handleResponse(response);
19+
};
20+
21+
return () => {
22+
global.fetch = originalFetch;
23+
};
24+
}, []);
25+
};
26+
27+
export default useFetchInterceptor;

pages/_app.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import { getInitialOrchestratorConfig } from '@/configuration';
3333
import { TranslationsProvider } from '@/translations/translationsProvider';
3434

3535
import '../font/inter.css';
36+
import useFetchInterceptor from "@/hooks/useFetchInterceptor";
3637

3738
type AppOwnProps = { orchestratorConfig: OrchestratorConfig };
3839

@@ -52,6 +53,7 @@ function CustomApp({
5253
}: AppProps & AppOwnProps) {
5354
const router = useRouter();
5455
const [queryClient] = useState(() => new QueryClient(queryClientConfig));
56+
useFetchInterceptor();
5557

5658
const [themeMode, setThemeMode] = useState<EuiThemeColorMode>(
5759
ColorModes.LIGHT,

0 commit comments

Comments
 (0)