-
Notifications
You must be signed in to change notification settings - Fork 12
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create RefreshSession High Order Component
The RefreshSession HOC adds 2 pieces of logic to the components: 1. it refreshes the session each 5 minutes, so if a token is expired it will try to refresh after 5minutes. 2. it checks if the token is expired on the window focus, and if it is expired it will try to refresh the token. This component is basically a wrapper for those funcionalities and it was made as a HOC instead of a hooks because it needed to be used within `providers.tsx` but it needed to be under `SessionProvider` since it uses the `useSession` hook.
- Loading branch information
1 parent
e4d53dd
commit 2e6c68f
Showing
2 changed files
with
46 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { useSession } from 'next-auth/react' | ||
import { useEffect } from 'react' | ||
|
||
const FIVE_MINUTES_IN_MILISSECONDS = 1000 * 60 * 5 | ||
|
||
export const RefreshSession = ({ children }: { children: React.ReactNode }) => { | ||
// update() triggers the jwt callback on next-auth/route.ts | ||
const { update, data } = useSession({ | ||
required: true | ||
}) | ||
|
||
// Refresh the session on a time interval | ||
useEffect(() => { | ||
// TIP: You can also use `navigator.onLine` and some extra event handlers | ||
// to check if the user is online and only update the session if they are. | ||
// https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine | ||
const interval = setInterval(() => update(), FIVE_MINUTES_IN_MILISSECONDS) | ||
return () => clearInterval(interval) | ||
}, [update]) | ||
|
||
// Refresh the session on window re-focus if the token is expired | ||
useEffect(() => { | ||
const visibilityHandler = () => { | ||
if ( | ||
document.visibilityState === 'visible' && | ||
data?.accessTokenExpires && | ||
Date.now() > data.accessTokenExpires | ||
) { | ||
update() | ||
} | ||
} | ||
|
||
window.addEventListener('visibilitychange', visibilityHandler, false) | ||
return () => window.removeEventListener('visibilitychange', visibilityHandler, false) | ||
}, [data, update]) | ||
|
||
return children | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters