日本語

“React: Warn Before Auto-Logout and Let Users Extend the Session”

​​React​Accessibility,custom hook,dialog,localStorage,Playwright,TypeScript

On a screen that logs the user out after a period of inactivity, showing a dialog with the remaining time shortly before logout, along with a button to extend the session, prevents the user from being logged out in the middle of typing. Here I build a useIdleTimeout hook that holds only one value, the logout time (the deadline), and switches between "normal", "warning", and "logged out" based on the difference between that deadline and the current time. I also build the dialog that shows the warning.

In a test environment, I built a screen that logs out after 10 minutes of inactivity and shows a warning with 60 seconds left. I advanced the clock with Playwright and checked when the warning appears, extension, the Esc key, and behavior across multiple tabs.

Note

The test environment is Ubuntu 24.04 and Node.js 22.23.4. I used react and react-dom 19.3.1, @types/react 19.3.0, typescript 7.0.2, and esbuild 0.28.2. I type-checked the .tsx files with tsc, converted them with esbuild, and operated Chromium 153 with Playwright 1.63.0. Time was checked by advancing a clock frozen with Playwright's Clock. I did not actually wait 10 minutes on a real clock. I did not test Firefox or Safari, behavior when a tab is actually sent to the background or the OS actually sleeps, screen reader announcements, or integration with the server-side session.

Show a Dialog at 60 Seconds Left; Pressing the Button Adds 10 Minutes

Here is the behavior I built. At exactly 9:09, the dialog appears and the remaining seconds count down. Pressing the Stay logged in button closes the dialog and moves the logout time to 10 minutes after the moment of pressing.

A warning dialog that appears one minute before automatic logout. Pressing the Stay logged in button closes the dialog and extends the scheduled logout time.
Pressing the Stay logged in button in the dialog that appears with 60 seconds left extends the scheduled logout from 9:10:00 to 9:19:04. The following 9 minutes are sped up at one frame per minute.

The bar at the top of the screen was overlaid for the GIF. The "scheduled logout" label in that bar is the deadline the hook saved, displayed as-is.

For the length of the warning period, I used WCAG 2.2 Success Criterion 2.2.1 (Timing Adjustable) as a guideline. When the user can extend the session, the criterion requires warning before the deadline, giving at least 20 seconds to extend with a simple action such as pressing the space bar, and allowing at least 10 extensions. I chose 60 seconds to leave some margin. I did not set a limit on the number of extensions.

Keep One Deadline and Derive the Remaining Time from the Current Time

Here is the whole hook.

ts
import { useCallback, useEffect, useEffectEvent, useRef, useState } from 'react';

export type Phase = 'active' | 'warning' | 'expired';

type Options = {
  timeoutMs: number; // Log out after this much time with no activity
  warningMs: number; // Show the warning this long before logout
  onTimeout: () => void;
  storageKey?: string;
};

// Events that count as activity
const ACTIVITY_EVENTS = ['pointerdown', 'pointermove', 'keydown', 'wheel'] as const;

// If localStorage is unavailable, work only within this tab
function readShared(key: string): number | null {
  try {
    const n = Number(localStorage.getItem(key) ?? NaN);
    return Number.isFinite(n) ? n : null; // Ignore when the value is missing or not a number
  } catch {
    return null;
  }
}
function writeShared(key: string, deadline: number) {
  try {
    localStorage.setItem(key, String(deadline));
  } catch {}
}

export function useIdleTimeout({ timeoutMs, warningMs, onTimeout, storageKey = 'session-deadline' }: Options) {
  const [phase, setPhase] = useState<Phase>('active');
  const [remainingSec, setRemainingSec] = useState(0);
  const deadlineRef = useRef(0); // Logout time (a Date.now() value)
  const phaseRef = useRef<Phase>('active');
  const handleTimeout = useEffectEvent(onTimeout);

  // Set a new deadline and tell other tabs
  const setDeadline = useCallback(
    (deadline: number) => {
      deadlineRef.current = deadline;
      writeShared(storageKey, deadline);
    },
    [storageKey],
  );

  // Recompute the state from the difference between now and the deadline
  const check = useCallback(() => {
    if (phaseRef.current === 'expired') return;
    const shared = readShared(storageKey);
    if (shared !== null) deadlineRef.current = shared; // Follow the deadline if another tab extended it
    const remaining = deadlineRef.current - Date.now();
    const next: Phase = remaining <= 0 ? 'expired' : remaining <= warningMs ? 'warning' : 'active';
    phaseRef.current = next;
    setPhase(next);
    setRemainingSec(next === 'warning' ? Math.ceil(remaining / 1000) : 0);
  }, [storageKey, warningMs]);

  useEffect(() => {
    if (phase === 'expired') handleTimeout();
  }, [phase]);

  useEffect(() => {
    setDeadline(Date.now() + timeoutMs); // Treat the time of opening as the first activity
    check();
    const id = setInterval(check, 500);

    const onActivity = () => {
      if (phaseRef.current !== 'active') return; // Do not extend during a warning
      const next = Date.now() + timeoutMs;
      if (next - deadlineRef.current < 1000) return; // Write at most once per second
      setDeadline(next);
    };
    // Timers in background tabs run late, so check right away when the tab becomes visible again
    const onVisible = () => {
      if (document.visibilityState === 'visible') check();
    };
    for (const type of ACTIVITY_EVENTS) window.addEventListener(type, onActivity, { passive: true });
    document.addEventListener('visibilitychange', onVisible);
    return () => {
      clearInterval(id);
      for (const type of ACTIVITY_EVENTS) window.removeEventListener(type, onActivity);
      document.removeEventListener('visibilitychange', onVisible);
    };
  }, [check, setDeadline, timeoutMs]);

  const extend = useCallback(() => {
    if (phaseRef.current === 'expired') return;
    setDeadline(Date.now() + timeoutMs);
    check();
  }, [check, setDeadline, timeoutMs]);

  const logout = useCallback(() => {
    setDeadline(0); // Set the deadline to the past. Other tabs will log out on their next check
    check();
  }, [check, setDeadline]);

  return { phase, remainingSec, extend, logout };
}

The logout time is held in deadlineRef as a Date.now() value. Because it changes with every user action, I made it a ref rather than state. The only values the screen needs are phase, which indicates whether the state is "normal", "warning", or "logged out", and remainingSec, the remaining seconds during the warning.

check runs every 0.5 seconds and recomputes phase from the difference between the deadline and the current time. During normal operation, remainingSec stays at 0, so the same values are passed to setPhase and setRemainingSec each time. React skips re-rendering when the new value is Object.is-equal to the current state, so even though check runs every 0.5 seconds during normal operation, child components are not re-rendered.

I compute the remaining time from the difference each time instead of counting down by 1 each second, because timers can fall behind. According to MDN's setTimeout page, Chrome, under some conditions such as for a tab that has been hidden for more than 5 minutes, checks timers only once per minute. If the state is derived from the difference, it will be correct the next time the code runs, even if the timer was late. When the tab becomes visible again, I call check immediately through the visibilitychange event of the Page Visibility API.

I also tested the case where the timer did not run at all for 15 minutes. Playwright's page.clock.fastForward skips the clock forward and runs scheduled timers at most once during that time. According to the official explanation, this is the same as when a laptop lid has been closed for a while. I did not actually put the machine to sleep, but I created a similar condition with clock control. When I skipped 15 minutes right after opening the page, the screen went straight to the logged-out view without showing the warning dialog at all.

text
開いた直後                    9:00:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
15分飛ばした                  9:15:00.0 | ログアウトしました | ダイアログ: 閉じている | 保存された期限 9:10:00.0
onTimeout が呼ばれた回数: 1
ダイアログの開閉: []

The logout handler (onTimeout) is called from an effect that runs when phase changes to 'expired'. The function passed in is wrapped with useEffectEvent, so even if the parent passes a new function on every render, it is not added to the effect's dependencies. In both the development build with StrictMode and the production build, onTimeout was called exactly once.

After the Warning, Extend Only When the Button Is Pressed

onActivity resets the deadline to "10 minutes from now" on every mouse or keyboard action, but only while phase is normal. If the mouse moves slightly after the warning appears and the dialog closes, the user may not notice that a warning appeared. So during a warning, I made the user explicitly choose to extend the session, either with the Stay logged in button or the Esc key.

Here are the results of checking the behavior before and after the warning in a single tab. The left column shows the action, and the right side shows the time, the screen state, and the saved deadline.

text
開いた直後                        9:00:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
8分59.5秒後                     9:08:59.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
9分後                          9:09:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:10:00.0
  フォーカスのある要素: ログインを続ける
警告中にマウスとキーを操作                9:09:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:10:00.0
さらに30秒後                      9:09:30.0 | マイページ | ダイアログ: 開いている(あと 30 秒) | 保存された期限 9:10:00.0
「ログインを続ける」を押した               9:09:30.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:19:30.0
8分59.5秒後                     9:18:29.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:19:30.0
さらに0.5秒後                     9:18:30.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:19:30.0
Esc キーを押した                   9:18:30.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:28:30.0
9分59.5秒後(何もしない)              9:28:29.5 | マイページ | ダイアログ: 開いている(あと 1 秒) | 保存された期限 9:28:30.0
さらに0.5秒後                     9:28:30.0 | ログアウトしました | ダイアログ: 閉じている | 保存された期限 9:28:30.0
onTimeout が呼ばれた回数: 1
ダイアログの開閉: 9:09:00.0 開いた / 9:09:30.0 閉じた / 9:18:30.0 開いた / 9:18:30.0 閉じた / 9:27:30.0 開いた / 9:28:30.0 閉じた

The dialog opened at exactly 9 minutes, and focus was on the Stay logged in button. Even when I moved the mouse and pressed keys during the warning, the deadline stayed at 9:10:00, and 30 seconds later 30 seconds remained. Pressing the button set the deadline to 10 minutes after the press time, 9:09:30. When I did nothing afterward, the screen switched to the logged-out view at the deadline of 9:28:30.

Before the warning, the activity events include ones such as pointermove that arrive many times over a short interval. I rewrote the deadline only when it would extend the current deadline by at least 1 second. Here are the results after 3 minutes, when I moved the mouse 150 times over 3 seconds (every 0.02 seconds).

text
3分後                            9:03:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
3秒間マウスを150回動かした                9:03:03.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:13:02.0
  その間の localStorage への書き込み: 3 回
さらに8分58.5秒後                    9:12:01.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:13:02.0
さらに0.5秒後                       9:12:02.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:13:02.0

There were only 3 writes to localStorage, and the deadline became 10 minutes after the last write at 9:03:02. The warning also appeared one minute before the deadline, at 9:12:02.

Show the Warning with showModal on a dialog Element

The dialog is opened with showModal() on the HTML dialog element.

tsx
import { useEffect, useRef } from 'react';

type Props = {
  open: boolean;
  remainingSec: number;
  onExtend: () => void;
  onLogout: () => void;
};

export function TimeoutDialog({ open, remainingSec, onExtend, onLogout }: Props) {
  const ref = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    const dialog = ref.current!;
    if (open && !dialog.open) dialog.showModal();
    if (!open && dialog.open) dialog.close();
  }, [open]);

  return (
    <dialog
      ref={ref}
      aria-labelledby="timeout-title"
      aria-describedby="timeout-desc"
      onCancel={(e) => {
        e.preventDefault(); // Do not close on Esc; treat it as an extension
        onExtend();
      }}
    >
      <h2 id="timeout-title">まもなく自動でログアウトします</h2>
      <p id="timeout-desc">
        操作がないため、あと <strong className="sec">{remainingSec}</strong> 秒でログアウトします。
      </p>
      <button type="button" onClick={onExtend}>ログインを続ける</button>
      <button type="button" onClick={onLogout}>今すぐログアウト</button>
    </dialog>
  );
}

As described on MDN's showModal() page, when opened with showModal(), the elements outside the dialog are inert and cannot be operated. In testing, the first button, Stay logged in, had focus immediately after the dialog opened.

Pressing the Esc key fires a cancel event on the dialog element. If nothing is done, the browser closes the dialog. So I call preventDefault() to stop the browser from closing it and treat the key press as an extension. The only place the dialog is closed is the effect that runs when open changes to false.

I compared the cases with and without onCancel, pressing Esc right after the warning appeared. With onCancel, the deadline is extended to 9:19:00.

text
9分後                  9:09:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:10:00.0
Esc キーを押した           9:09:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:19:00.0
さらに59.5秒後            9:09:59.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:19:00.0
さらに0.5秒後             9:10:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:19:00.0

Without onCancel, the dialog closed, but the deadline stayed at 9:10:00, and the user was logged out one minute later with no notice. The hook's phase remained in the warning state, so open did not change from true and the dialog was not reopened.

text
9分後                  9:09:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:10:00.0
Esc キーを押した           9:09:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
さらに59.5秒後            9:09:59.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
さらに0.5秒後             9:10:00.0 | ログアウトしました | ダイアログ: 閉じている | 保存された期限 9:10:00.0

Using It in a Component

Here is a screen that combines the hook and the dialog. When the user logs out, App switches to the "logged out" screen.

tsx
import { useState } from 'react';
import { TimeoutDialog } from './TimeoutDialog';
import { useIdleTimeout } from './useIdleTimeout';

function Session({ onTimeout }: { onTimeout: () => void }) {
  const { phase, remainingSec, extend, logout } = useIdleTimeout({
    timeoutMs: 10 * 60 * 1000,
    warningMs: 60 * 1000,
    onTimeout,
  });
  return (
    <main>
      <h1>マイページ</h1>
      <p>操作がないまま10分たつと、自動でログアウトします。</p>
      <TimeoutDialog open={phase === 'warning'} remainingSec={remainingSec} onExtend={extend} onLogout={logout} />
    </main>
  );
}

export function App() {
  const [loggedIn, setLoggedIn] = useState(true);
  if (!loggedIn) {
    return (
      <main>
        <h1>ログアウトしました</h1>
        <button type="button" onClick={() => setLoggedIn(true)}>もう一度ログイン</button>
      </main>
    );
  }
  return (
    <Session
      onTimeout={() => {
        console.log('onTimeout が呼ばれた');
        setLoggedIn(false);
      }}
    />
  );
}
Warning

Automatic logout on the client side is a way to inform the user. The OWASP Session Management Cheat Sheet states that session expiration must be enforced on the server side, because values and times in the browser can be altered. In a real application, onTimeout should call the server-side logout, and "Stay logged in" should also send a request to the server to extend the session. The tests in this article did not include any server communication.

A server usually counts from the last time it received a request. If the session is extended only by actions on the screen, the screen may still show the normal state after the server-side session has already expired. When extending through user actions, you need to send requests to the server from time to time, or align the screen's timing with the server's deadline. The Automatic Client Logout section of the same page also has an example that shows a warning with a countdown.

Keep the Deadline in Sync Across Multiple Tabs

If the same site is open in two tabs and each tab holds its own deadline, the tab you are not working in will decide there has been no activity and show the warning, even though you are working in the other tab. So I stored the deadline in localStorage. localStorage is shared among pages of the same origin, so a deadline written in one tab is read and synchronized by check in the other tabs within 0.5 seconds.

Here are the results when I opened the same browser with two tabs and operated only tab A. The clock stopped in Playwright is shared by both tabs.

text
2つのタブを開いた直後
  タブA 9:00:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
  タブB 9:00:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:10:00.0
5分後にタブAをクリックした(0.5秒後)
  タブA 9:05:00.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:15:00.0
  タブB 9:05:00.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:15:00.0
9分30秒後
  タブA 9:09:30.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:15:00.0
  タブB 9:09:30.0 | マイページ | ダイアログ: 閉じている | 保存された期限 9:15:00.0
14分後
  タブA 9:14:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:15:00.0
  タブB 9:14:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:15:00.0
タブAで「ログインを続ける」を押した(0.5秒後)
  タブA 9:14:00.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:24:00.0
  タブB 9:14:00.5 | マイページ | ダイアログ: 閉じている | 保存された期限 9:24:00.0
さらに9分後
  タブA 9:23:00.5 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:24:00.0
  タブB 9:23:00.5 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 9:24:00.0
タブAで「今すぐログアウト」を押した(0.5秒後)
  タブA 9:23:01.0 | ログアウトしました | ダイアログ: 閉じている | 保存された期限 0
  タブB 9:23:01.0 | ログアウトしました | ダイアログ: 閉じている | 保存された期限 0
onTimeout が呼ばれた回数: タブA 1 / タブB 1

When I clicked tab A 5 minutes in, the deadline in tab B was also extended to 9:15:00, and at 9 minutes 30 seconds neither tab showed a warning. At 14 minutes, both tabs showed the warning. When I pressed Stay logged in in tab A, the warning in tab B also closed. When I pressed Log out now in tab A, the deadline became 0, and tab B also logged out at its next check.

localStorage may be unavailable depending on browser settings. I wrapped the contents of readShared and writeShared in try/catch, so that if localStorage is unavailable, the hook works with a deadline held only within that tab. When I made getItem and setItem throw exceptions and tested in a single tab, the warning, extension, and logout happened at the same times as usual.

text
開いた直後                  9:00:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 (localStorage が使えない)
9分後                    9:09:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 (localStorage が使えない)
「ログインを続ける」を押した         9:09:00.0 | マイページ | ダイアログ: 閉じている | 保存された期限 (localStorage が使えない)
8分59.5秒後               9:17:59.5 | マイページ | ダイアログ: 閉じている | 保存された期限 (localStorage が使えない)
さらに0.5秒後               9:18:00.0 | マイページ | ダイアログ: 開いている(あと 60 秒) | 保存された期限 (localStorage が使えない)
さらに60秒後                9:19:00.0 | ログアウトしました | ダイアログ: 閉じている | 保存された期限 (localStorage が使えない)
onTimeout が呼ばれた回数: 1

​Posted by 86