Session
A session that renews while in use, expires when it isn't, and signs out every tab together.
session
signed out
Mounted
Sign in and the countdown renews on its own. Turn off keep renewing and it runs out. Open a second tab and sign out there: this one follows.
tsx
// react-graft-session-demo.tsx
export const ReactGraftSessionDemo = () => (
<ReactGraftSessionGraft.Provider>
<ReactGraftSessionPanel />
</ReactGraftSessionGraft.Provider>
);The graft
A hook holds the token and its deadline. The graft adds whether to keep renewing, and three effects.
tsx
// react-graft-session.graft.ts
export const ReactGraftSessionGraft = createGraft({
name: "ReactGraftSessionGraft",
graft: useGraft,
inject: [useInjectRenew, useInjectExpire, useInjectSyncTabs],
});
function useGraft({ lifetime = LIFETIME }: { lifetime?: number }) {
const session = useSession({ lifetime });
const [isRenewing, setIsRenewing] = useState(true);
return { ...session, isRenewing, setIsRenewing };
}Renewing and expiring
Two injected effects: one renews while in use, the other signs out when time runs out.
tsx
// renew shortly before it runs out, as long as it is meant to stay alive
function useInjectRenew({ isAuthorized, isRenewing, renew, secondsLeft }: SessionValue) {
useEffect(() => {
if (!isAuthorized || !isRenewing || secondsLeft > RENEW_LEAD) return;
renew();
}, [isAuthorized, isRenewing, renew, secondsLeft]);
}
// and when it does run out, end it
function useInjectExpire({ isAuthorized, secondsLeft, signOut }: SessionValue) {
useEffect(() => {
if (!isAuthorized || secondsLeft > 0) return;
signOut();
}, [isAuthorized, secondsLeft, signOut]);
}Across tabs
The third effect tells the other tabs when the session ends, and listens for them. It has to run even when nothing on screen is about the session, which is why it is injected.
tsx
// signing out anywhere signs out everywhere
function useInjectSyncTabs({ isAuthorized, signOut }: SessionValue) {
const wasAuthorized = useRef(isAuthorized);
useEffect(() => {
if (wasAuthorized.current && !isAuthorized) {
window.localStorage.setItem(SIGNOUT_KEY, String(Date.now()));
}
wasAuthorized.current = isAuthorized;
}, [isAuthorized]);
useEffect(() => {
const onStorage = (event: StorageEvent) => {
if (event.key !== SIGNOUT_KEY) return;
signOut();
};
window.addEventListener("storage", onStorage);
return () => window.removeEventListener("storage", onStorage);
}, [signOut]);
}The hook
State and a tick. The rules about renewing, expiring and tabs are in the graft.
tsx
// react-graft-session.graft.ts
function useSession({ lifetime }: { lifetime: number }) {
const [session, setSession] = useState<Session | null>(null);
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
if (!session) return;
const interval = setInterval(() => setNow(Date.now()), 500);
return () => clearInterval(interval);
}, [session]);
const signIn = useCallback(() => {
setNow(Date.now());
setSession({ token: newToken(), expiresAt: Date.now() + lifetime * 1000 });
}, [lifetime]);
const signOut = useCallback(() => setSession(null), []);
const renew = useCallback(
() => setSession((previous) => (previous ? { ...previous, expiresAt: Date.now() + lifetime * 1000 } : previous)),
[lifetime],
);
return {
token: session?.token ?? null,
isAuthorized: session !== null,
secondsLeft: session ? Math.max(0, Math.ceil((session.expiresAt - now) / 1000)) : 0,
renew,
signIn,
signOut,
};
}