Skip to content

⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.

fix(web): signing out no longer flashes an empty app (#781)

Pasqual Troncone710f2bdee92a
diff --git a/apps/web/messages/ar/common.json b/apps/web/messages/ar/common.json
index 4987443c..652e5bd1 100644
--- a/apps/web/messages/ar/common.json
+++ b/apps/web/messages/ar/common.json
@@ -217,5 +217,6 @@
"perPage": "لكل صفحة",
"range": "{first}-{last} من {total}"
},
- "aboutCloudAndPro": "اعرف المزيد عن Cloud وPro"
+ "aboutCloudAndPro": "اعرف المزيد عن Cloud وPro",
+ "signingOut": "جارٍ تسجيل الخروج…"
}
diff --git a/apps/web/messages/en/common.json b/apps/web/messages/en/common.json
index 527006de..693ad2ad 100644
--- a/apps/web/messages/en/common.json
+++ b/apps/web/messages/en/common.json
@@ -217,5 +217,6 @@
"perPage": "per page",
"range": "{first}-{last} of {total}"
},
- "aboutCloudAndPro": "Learn about Cloud and Pro"
+ "aboutCloudAndPro": "Learn about Cloud and Pro",
+ "signingOut": "Signing out…"
}
diff --git a/apps/web/messages/es-ES/common.json b/apps/web/messages/es-ES/common.json
index e0565825..2f262513 100644
--- a/apps/web/messages/es-ES/common.json
+++ b/apps/web/messages/es-ES/common.json
@@ -217,5 +217,6 @@
"perPage": "por página",
"range": "{first}-{last} de {total}"
},
- "aboutCloudAndPro": "Más sobre Cloud y Pro"
+ "aboutCloudAndPro": "Más sobre Cloud y Pro",
+ "signingOut": "Cerrando sesión…"
}
diff --git a/apps/web/messages/fa/common.json b/apps/web/messages/fa/common.json
index d8e9b295..5b5a6008 100644
--- a/apps/web/messages/fa/common.json
+++ b/apps/web/messages/fa/common.json
@@ -217,5 +217,6 @@
"perPage": "در هر صفحه",
"range": "{first}-{last} از {total}"
},
- "aboutCloudAndPro": "درباره Cloud و Pro"
+ "aboutCloudAndPro": "درباره Cloud و Pro",
+ "signingOut": "در حال خروج…"
}
diff --git a/apps/web/messages/fr/common.json b/apps/web/messages/fr/common.json
index 4815e897..75cbf8b2 100644
--- a/apps/web/messages/fr/common.json
+++ b/apps/web/messages/fr/common.json
@@ -217,5 +217,6 @@
"perPage": "par page",
"range": "{first}-{last} sur {total}"
},
- "aboutCloudAndPro": "En savoir plus sur Cloud et Pro"
+ "aboutCloudAndPro": "En savoir plus sur Cloud et Pro",
+ "signingOut": "Déconnexion…"
}
diff --git a/apps/web/messages/id/common.json b/apps/web/messages/id/common.json
index 24f52c71..86476db0 100644
--- a/apps/web/messages/id/common.json
+++ b/apps/web/messages/id/common.json
@@ -217,5 +217,6 @@
"perPage": "per halaman",
"range": "{first}-{last} dari {total}"
},
- "aboutCloudAndPro": "Pelajari Cloud dan Pro"
+ "aboutCloudAndPro": "Pelajari Cloud dan Pro",
+ "signingOut": "Sedang keluar…"
}
diff --git a/apps/web/messages/ko/common.json b/apps/web/messages/ko/common.json
index 554acaae..608bf458 100644
--- a/apps/web/messages/ko/common.json
+++ b/apps/web/messages/ko/common.json
@@ -217,5 +217,6 @@
"perPage": "개씩 보기",
"range": "전체 {total}개 중 {first}-{last}"
},
- "aboutCloudAndPro": "Cloud 및 Pro 알아보기"
+ "aboutCloudAndPro": "Cloud 및 Pro 알아보기",
+ "signingOut": "로그아웃하는 중…"
}
diff --git a/apps/web/messages/pt-BR/common.json b/apps/web/messages/pt-BR/common.json
index 6c844472..23e0c626 100644
--- a/apps/web/messages/pt-BR/common.json
+++ b/apps/web/messages/pt-BR/common.json
@@ -217,5 +217,6 @@
"perPage": "por página",
"range": "{first}-{last} de {total}"
},
- "aboutCloudAndPro": "Saiba mais sobre Cloud e Pro"
+ "aboutCloudAndPro": "Saiba mais sobre Cloud e Pro",
+ "signingOut": "Saindo…"
}
diff --git a/apps/web/messages/ru/common.json b/apps/web/messages/ru/common.json
index a787344b..24a0a304 100644
--- a/apps/web/messages/ru/common.json
+++ b/apps/web/messages/ru/common.json
@@ -217,5 +217,6 @@
"perPage": "на странице",
"range": "{first}-{last} из {total}"
},
- "aboutCloudAndPro": "Подробнее о Cloud и Pro"
+ "aboutCloudAndPro": "Подробнее о Cloud и Pro",
+ "signingOut": "Выход…"
}
diff --git a/apps/web/messages/tr/common.json b/apps/web/messages/tr/common.json
index efcd59ed..821cde21 100644
--- a/apps/web/messages/tr/common.json
+++ b/apps/web/messages/tr/common.json
@@ -217,5 +217,6 @@
"perPage": "/ sayfa",
"range": "{total} kayıttan {first}-{last} arası"
},
- "aboutCloudAndPro": "Cloud ve Pro hakkında bilgi edinin"
+ "aboutCloudAndPro": "Cloud ve Pro hakkında bilgi edinin",
+ "signingOut": "Oturum kapatılıyor…"
}
diff --git a/apps/web/messages/uk/common.json b/apps/web/messages/uk/common.json
index 1a77e592..037130a9 100644
--- a/apps/web/messages/uk/common.json
+++ b/apps/web/messages/uk/common.json
@@ -217,5 +217,6 @@
"perPage": "на сторінці",
"range": "{first}-{last} з {total}"
},
- "aboutCloudAndPro": "Докладніше про Cloud і Pro"
+ "aboutCloudAndPro": "Докладніше про Cloud і Pro",
+ "signingOut": "Вихід…"
}
diff --git a/apps/web/messages/zh-CN/common.json b/apps/web/messages/zh-CN/common.json
index 3646e0d8..a8d514b7 100644
--- a/apps/web/messages/zh-CN/common.json
+++ b/apps/web/messages/zh-CN/common.json
@@ -217,5 +217,6 @@
"perPage": "每页",
"range": "第 {first}-{last} 项,共 {total} 项"
},
- "aboutCloudAndPro": "了解 Cloud 和 Pro"
+ "aboutCloudAndPro": "了解 Cloud 和 Pro",
+ "signingOut": "正在退出…"
}
diff --git a/apps/web/messages/zh-TW/common.json b/apps/web/messages/zh-TW/common.json
index 4e00fc6c..deff295b 100644
--- a/apps/web/messages/zh-TW/common.json
+++ b/apps/web/messages/zh-TW/common.json
@@ -217,5 +217,6 @@
"perPage": "每頁",
"range": "第 {first}-{last} 項,共 {total} 項"
},
- "aboutCloudAndPro": "瞭解 Cloud 和 Pro"
+ "aboutCloudAndPro": "瞭解 Cloud 和 Pro",
+ "signingOut": "正在登出…"
}
diff --git a/apps/web/src/components/layout/UserMenu.tsx b/apps/web/src/components/layout/UserMenu.tsx
index 1018e008..9a28aeb9 100644
--- a/apps/web/src/components/layout/UserMenu.tsx
+++ b/apps/web/src/components/layout/UserMenu.tsx
@@ -2,7 +2,6 @@
import { useEffect, useState } from 'react';
import Link from 'next/link';
-import { useRouter } from 'next/navigation';
import { LogOut } from 'lucide-react';
import { useTranslations } from 'next-intl';
import { signOut, useSession } from '@/lib/auth-client';
@@ -23,13 +22,11 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
// Signed-in user control in the header: shows the account avatar and a menu with
// the email, the role, links to preferences, connected accounts, account security
// (passkeys) and API keys, and sign out.
-// Signing out clears the session and the proxy sends the browser back to
-// the login page.
+// Signing out clears the session and loads the sign-in page itself.
export default function UserMenu() {
const t = useTranslations('nav');
const tCommon = useTranslations('common');
const sectionLabel = useAccountSectionLabel();
- const router = useRouter();
const { data: session, isPending } = useSession();
// better-auth reads the session on the client, so the server renders no user and
@@ -45,10 +42,8 @@ export default function UserMenu() {
const role = (user as { role?: string }).role ?? 'user';
const image = (user as { image?: string | null }).image ?? null;
- async function onSignOut() {
- await signOut();
- router.push('/login');
- router.refresh();
+ function onSignOut() {
+ void signOut();
}
return (
diff --git a/apps/web/src/components/providers.tsx b/apps/web/src/components/providers.tsx
index 8f64622f..941ee10d 100644
--- a/apps/web/src/components/providers.tsx
+++ b/apps/web/src/components/providers.tsx
@@ -13,6 +13,7 @@ import { RelativeTimeProvider } from '@/context/relativeTimeContext';
import { Toaster } from '@/components/ui/sonner';
import PreferencesSync from '@/components/preferences-sync';
import SessionScope from '@/components/session-scope';
+import SigningOutGate from '@/components/signing-out-gate';
// The message shown for a failed mutation: the API's `{ error }` text (carried by
// ApiError) when present, otherwise a generic fallback.
@@ -66,7 +67,9 @@ export function Providers({ children }: { children: ReactNode }) {
<PreferencesSync />
<SyncProvider>
<RelativeTimeProvider>
- <HotkeysProvider>{children}</HotkeysProvider>
+ <HotkeysProvider>
+ <SigningOutGate>{children}</SigningOutGate>
+ </HotkeysProvider>
</RelativeTimeProvider>
</SyncProvider>
<Toaster position={dir === 'rtl' ? 'bottom-left' : 'bottom-right'} dir={dir} richColors />
diff --git a/apps/web/src/components/signing-out-gate.test.tsx b/apps/web/src/components/signing-out-gate.test.tsx
new file mode 100644
index 00000000..68e17468
--- /dev/null
+++ b/apps/web/src/components/signing-out-gate.test.tsx
@@ -0,0 +1,68 @@
+import assert from 'node:assert/strict';
+import { afterEach, beforeEach, it } from 'node:test';
+import { act } from 'react';
+import type { Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { JSDOM, VirtualConsole } from 'jsdom';
+import { markSignedIn } from '@/lib/api/core/client';
+import { signOut } from '@/lib/auth-client';
+import common from '../../messages/en/common.json';
+import SigningOutGate from './signing-out-gate';
+
+let root: Root;
+let dom: JSDOM;
+let descriptors: Map<string, PropertyDescriptor | undefined>;
+
+beforeEach(async () => {
+ descriptors = new Map(
+ ['window', 'document', 'navigator', 'IS_REACT_ACT_ENVIRONMENT'].map((name) => [
+ name,
+ Object.getOwnPropertyDescriptor(globalThis, name),
+ ]),
+ );
+ // The sign-out ends in a page load, which jsdom only reports.
+ dom = new JSDOM('<div id="root"></div>', {
+ url: 'https://example.test/acme/MKT',
+ virtualConsole: new VirtualConsole(),
+ });
+ Object.defineProperties(globalThis, {
+ window: { configurable: true, value: dom.window },
+ document: { configurable: true, value: dom.window.document },
+ navigator: { configurable: true, value: dom.window.navigator },
+ IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true },
+ });
+ const { createRoot } = await import('react-dom/client');
+ root = createRoot(document.getElementById('root')!);
+ act(() =>
+ root.render(
+ <NextIntlClientProvider locale="en" messages={{ common }} timeZone="UTC">
+ <SigningOutGate>
+ <p>Board</p>
+ </SigningOutGate>
+ </NextIntlClientProvider>,
+ ),
+ );
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ // signOut marks lib/api as signing out, which would mute its 401 handling in later files.
+ markSignedIn();
+ dom.window.close();
+ for (const [name, descriptor] of descriptors) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else Reflect.deleteProperty(globalThis, name);
+ }
+});
+
+it('swaps the app for the signing-out screen as soon as a sign-out starts', async () => {
+ assert.equal(document.body.textContent, 'Board');
+
+ let leaving!: Promise<void>;
+ act(() => {
+ leaving = signOut();
+ });
+
+ assert.equal(document.body.textContent, 'Signing out…');
+ await act(() => leaving);
+});
diff --git a/apps/web/src/components/signing-out-gate.tsx b/apps/web/src/components/signing-out-gate.tsx
new file mode 100644
index 00000000..f5c22208
--- /dev/null
+++ b/apps/web/src/components/signing-out-gate.tsx
@@ -0,0 +1,29 @@
+'use client';
+
+import type { ReactNode } from 'react';
+import { Loader2 } from 'lucide-react';
+import { useTranslations } from 'next-intl';
+import AppLogo from '@/components/common/AppLogo';
+import { useSigningOut } from '@/lib/auth-client';
+
+// Swaps the app for a neutral screen while a sign-out leaves it: left mounted, the app
+// would draw empty pages and ask the api for data the gone session can no longer read
+// until the next page loads.
+export default function SigningOutGate({ children }: { children: ReactNode }) {
+ const t = useTranslations('common');
+ const signingOut = useSigningOut();
+
+ if (!signingOut) return children;
+ return (
+ <main
+ aria-live="polite"
+ className="flex min-h-svh flex-col items-center justify-center gap-4 bg-muted p-6"
+ >
+ <AppLogo className="size-10" />
+ <p className="flex items-center gap-2 text-sm text-muted-foreground">
+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
+ {t('signingOut')}
+ </p>
+ </main>
+ );
+}
diff --git a/apps/web/src/features/invite/components/InviteStep.tsx b/apps/web/src/features/invite/components/InviteStep.tsx
index 4fc6ab1e..97eedeaf 100644
--- a/apps/web/src/features/invite/components/InviteStep.tsx
+++ b/apps/web/src/features/invite/components/InviteStep.tsx
@@ -1,7 +1,6 @@
'use client';
import Link from 'next/link';
-import { useRouter } from 'next/navigation';
import { useTranslations } from 'next-intl';
import type { InviteView } from '@/lib/api/endpoints/invites';
import { signOut, useSession } from '@/lib/auth-client';
@@ -17,12 +16,10 @@ import InviteNotice from './InviteNotice';
export default function InviteStep({ token, invite }: { token: string; invite: InviteView }) {
const t = useTranslations('invite');
const tCommon = useTranslations('common');
- const router = useRouter();
const { data: session, isPending: sessionPending } = useSession();
- async function switchAccount() {
- await signOut();
- router.refresh();
+ function switchAccount() {
+ void signOut('here');
}
if (invite.status !== 'pending' || invite.expired) {
diff --git a/apps/web/src/lib/auth-client.test.ts b/apps/web/src/lib/auth-client.test.ts
index 1437a7d2..8edf4118 100644
--- a/apps/web/src/lib/auth-client.test.ts
+++ b/apps/web/src/lib/auth-client.test.ts
@@ -1,5 +1,7 @@
import assert from 'node:assert/strict';
-import { describe, it } from 'node:test';
+import { afterEach, before, beforeEach, describe, it } from 'node:test';
+import { JSDOM, VirtualConsole } from 'jsdom';
+import { markSignedIn } from '@/lib/api/core/client';
import { authBaseURL } from './auth-client';
describe('authBaseURL', () => {
@@ -18,3 +20,91 @@ describe('authBaseURL', () => {
);
});
});
+
+// signOut takes the app down and leaves the page itself, so no caller navigates inside
+// an app whose session is gone.
+const replacedGlobals = ['window', 'document', 'fetch'] as const;
+
+let dom: JSDOM;
+let originals: Map<string, PropertyDescriptor | undefined>;
+let signOut: typeof import('./auth-client').signOut;
+let isSigningOut: typeof import('./auth-client').isSigningOut;
+let signingOutAtRequest: boolean | null;
+// jsdom does not load other documents; it reports each attempt instead.
+let navigations: number;
+
+// better-auth keeps the fetch it finds when the client is created, and other test files
+// may have created the shared one already, so this file loads its own copy over a fetch
+// that answers through `answer`.
+let answer: (url: string) => Response;
+
+function fakeFetch(input: string | URL | Request) {
+ return Promise.resolve(answer(input instanceof Request ? input.url : String(input)));
+}
+
+before(async () => {
+ const original = Object.getOwnPropertyDescriptor(globalThis, 'fetch');
+ Object.defineProperty(globalThis, 'fetch', { configurable: true, value: fakeFetch });
+ const ownCopy = './auth-client.ts?sign-out-test';
+ ({ signOut, isSigningOut } = (await import(ownCopy)) as typeof import('./auth-client'));
+ if (original) Object.defineProperty(globalThis, 'fetch', original);
+});
+
+beforeEach(() => {
+ originals = new Map(
+ replacedGlobals.map((name) => [name, Object.getOwnPropertyDescriptor(globalThis, name)]),
+ );
+ navigations = 0;
+ const virtualConsole = new VirtualConsole();
+ virtualConsole.on('jsdomError', (error) => {
+ if (error.message.includes('navigation')) navigations++;
+ });
+ dom = new JSDOM('<!doctype html>', { url: 'https://example.test/acme/MKT', virtualConsole });
+ for (const name of ['window', 'document'] as const) {
+ Object.defineProperty(globalThis, name, { configurable: true, value: dom.window[name] });
+ }
+ signingOutAtRequest = null;
+ answer = (url) => {
+ if (!url.endsWith('/sign-out')) return Response.json(null);
+ signingOutAtRequest = isSigningOut();
+ return Response.json({ success: true });
+ };
+ Object.defineProperty(globalThis, 'fetch', { configurable: true, value: fakeFetch });
+});
+
+afterEach(() => {
+ // signOut marks lib/api as signing out, which would mute its 401 handling in later files.
+ markSignedIn();
+ for (const [name, descriptor] of originals) {
+ if (descriptor) Object.defineProperty(globalThis, name, descriptor);
+ else delete (globalThis as Record<string, unknown>)[name];
+ }
+ dom.window.close();
+});
+
+describe('signOut', () => {
+ it('takes the app down before the session goes, and keeps it down while leaving', async () => {
+ await signOut();
+
+ assert.equal(signingOutAtRequest, true);
+ assert.equal(isSigningOut(), true);
+ });
+
+ it('loads the next page as a full load, /login or the same page', async () => {
+ await signOut();
+ assert.equal(navigations, 1);
+
+ await signOut('here');
+ assert.equal(navigations, 2);
+ });
+
+ it('leaves even when the sign-out request fails', async () => {
+ answer = () => {
+ throw new TypeError('Failed to fetch');
+ };
+
+ await signOut();
+
+ assert.equal(navigations, 1);
+ });
+});
diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts
index 1a44f1e9..71de7448 100644
--- a/apps/web/src/lib/auth-client.ts
+++ b/apps/web/src/lib/auth-client.ts
@@ -1,3 +1,4 @@
+import { useSyncExternalStore } from 'react';
import { createAuthClient } from 'better-auth/react';
import { inferAdditionalFields } from 'better-auth/client/plugins';
import { magicLinkClient, usernameClient } from 'better-auth/client/plugins';
@@ -63,12 +64,42 @@ export const {
unlinkAccount,
} = authClient;
+// True from the start of a sign-out until the browser leaves the page. SigningOutGate
+// swaps the app for a neutral screen meanwhile, so nothing on it asks the api for data
+// once the session is gone.
+let signingOut = false;
+const signingOutListeners = new Set<() => void>();
+
+export function isSigningOut(): boolean {
+ return signingOut;
+}
+
+export function useSigningOut(): boolean {
+ return useSyncExternalStore(
+ (listener) => {
+ signingOutListeners.add(listener);
+ return () => signingOutListeners.delete(listener);
+ },
+ isSigningOut,
+ () => false,
+ );
+}
+
// Sign out through this wrapper rather than through the client: it tells lib/api
// that the 401s the dropped session causes are expected, so they do not send the
-// browser to the expired-session screen.
-export async function signOut() {
+// browser to the expired-session screen. It then loads /login, or with `here` the same
+// page, as a full load: navigating inside the app would draw it again with no session.
+export async function signOut(then: 'login' | 'here' = 'login'): Promise<void> {
markSigningOut();
- return authClient.signOut();
+ signingOut = true;
+ for (const listener of signingOutListeners) listener();
+ // Lets React take the app down before the session goes.
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ // Leaves whatever the sign-out answered, as lib/api's endSession does: a failed
+ // request must not hold the browser on the signing-out screen.
+ await authClient.signOut().catch(() => {});
+ if (then === 'here') window.location.reload();
+ else window.location.replace('/login');
}
export type SessionUser = typeof authClient.$Infer.Session.user;