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): stop the redirect loop on a stale session cookie (#319)

Croff2e392a3f4c76
diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts
index d02b570a..cbe0307b 100644
--- a/apps/web/src/lib/api.ts
+++ b/apps/web/src/lib/api.ts
@@ -60,8 +60,9 @@ export function markSignedIn(): void {
// A 401 means the session behind the cookie is gone. The proxy only checks that a
// session cookie exists, so a stale one keeps the app open on a page where every
-// request fails. Signing out is what drops the cookie; with it still set the proxy
-// would bounce /login straight back into the app.
+// request fails. Sign out to drop the cookie, then leave for the expired screen
+// whatever the sign-out answered — a cookie the server declines to clear must not
+// hold the browser in the app.
// The request is written out rather than calling `signOut()` from @/lib/auth-client:
// that module reads API_URL from this one, so importing it back here would make a
// cycle that evaluates auth-client before API_URL is assigned.
@@ -69,15 +70,8 @@ function endSession(): void {
if (typeof window === 'undefined' || signingOut) return;
signingOut = true;
void fetch(`${API_URL}/api/auth/sign-out`, { method: 'POST', credentials: 'include' })
- .then((res) => {
- // Leaving with the cookie still set sends the proxy straight back into the
- // app, where the next 401 starts this over as a fresh page load.
- if (res.ok) window.location.replace('/login?expired=1');
- else signingOut = false;
- })
- .catch(() => {
- signingOut = false;
- });
+ .catch(() => {})
+ .then(() => window.location.replace('/login?expired=1'));
}
// Turns a failed response into the error to throw, and catches an ended session on
diff --git a/apps/web/src/proxy.test.ts b/apps/web/src/proxy.test.ts
new file mode 100644
index 00000000..372fef10
--- /dev/null
+++ b/apps/web/src/proxy.test.ts
@@ -0,0 +1,42 @@
+import assert from 'node:assert/strict';
+import { describe, it } from 'node:test';
+import { NextRequest } from 'next/server';
+import { proxy } from './proxy';
+
+const COOKIE = 'better-auth.session_token=stale.signature';
+
+function run(path: string, cookie?: string) {
+ return proxy(
+ new NextRequest(`http://localhost${path}`, {
+ headers: cookie ? { cookie } : undefined,
+ }),
+ );
+}
+
+describe('proxy', () => {
+ it('keeps a stale session on the expired screen instead of bouncing it back', () => {
+ const res = run('/login?expired=1', COOKIE);
+ assert.equal(res.headers.get('location'), null);
+ });
+
+ it('expires the stale cookies the api could not clear', () => {
+ const res = run('/login?expired=1', `${COOKIE}; __Secure-better-auth.session_data=cached`);
+ const cleared = res.headers.getSetCookie();
+ assert.equal(cleared.length, 2);
+ assert.match(cleared[0]!, /^better-auth\.session_token=;/);
+ assert.match(cleared[0]!, /Expires=Thu, 01 Jan 1970/);
+ // A `__Secure-` cookie is only accepted back with the attribute its name demands.
+ assert.match(cleared[1]!, /^__Secure-better-auth\.session_data=;/);
+ assert.match(cleared[1]!, /Secure/);
+ });
+
+ it('sends a signed-in user away from the login page', () => {
+ const res = run('/login', COOKIE);
+ assert.equal(res.headers.get('location'), 'http://localhost/');
+ });
+
+ it('sends a visitor without a session to the login page', () => {
+ const res = run('/', undefined);
+ assert.equal(res.headers.get('location'), 'http://localhost/login');
+ });
+});
diff --git a/apps/web/src/proxy.ts b/apps/web/src/proxy.ts
index 639543b2..c1711287 100644
--- a/apps/web/src/proxy.ts
+++ b/apps/web/src/proxy.ts
@@ -17,13 +17,24 @@ const PUBLIC_PATHS = ['/login', '/register'];
// content and must pass this session gate before their route forwards the cookie.
const OPEN_PATHS = ['/invite', '/forgot-password', '/reset-password', '/share', '/media'];
+// Expires every better-auth cookie the request carries. A `__Secure-` name is only
+// accepted back with `secure`, so the deletion carries it too.
+function clearSession(request: NextRequest): NextResponse {
+ const response = NextResponse.next();
+ for (const { name } of request.cookies.getAll()) {
+ if (!name.includes('better-auth.')) continue;
+ response.cookies.delete({ name, path: '/', secure: name.startsWith('__Secure-') });
+ }
+ return response;
+}
+
// Gate the whole app behind a session. This is an optimistic check: it only looks
// for the presence of the better-auth session cookie, not its validity — the API
// does the real validation on every request. It keeps unauthenticated users out of
// the planner UI and bounces signed-in users away from the auth pages.
// A cookie the API no longer accepts passes this check, so the client handles that
// case: `apiFailure` in `lib/api.ts` signs out on a 401 and lands on
-// `/login?expired=1`.
+// `/login?expired=1`, where the cookie is cleared for good.
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
const hasSession = getSessionCookie(request) != null;
@@ -34,6 +45,11 @@ export function proxy(request: NextRequest) {
const isPublic = PUBLIC_PATHS.some(matches);
if (isPublic) {
+ // The client lands here after the API refused the session. Its sign-out misses a
+ // cookie written under attributes the api no longer sets, and that one passes the
+ // check below and bounces the browser back into the app, where the next 401 starts
+ // the cycle over.
+ if (request.nextUrl.searchParams.get('expired') === '1') return clearSession(request);
if (hasSession) return NextResponse.redirect(new URL('/', request.url));
return NextResponse.next();
}