diff --git a/src/app/components/AuthRedirectInstaller.tsx b/src/app/components/AuthRedirectInstaller.tsx
new file mode 100644
index 0000000..d216e6f
--- /dev/null
+++ b/src/app/components/AuthRedirectInstaller.tsx
@@ -0,0 +1,9 @@
+"use client";
+
+import { useEffect } from "react";
+import { installAuthRedirect } from "@/lib/authRedirect";
+
+export function AuthRedirectInstaller() {
+ useEffect(() => installAuthRedirect(), []);
+ return null;
+}
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index 1e707a3..1abeec1 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -1,6 +1,7 @@
import type { Metadata, Viewport } from "next";
import { NuqsAdapter } from "nuqs/adapters/next/app";
import { ThemeProvider, ThemedToaster } from "@/providers/ThemeProvider";
+import { AuthRedirectInstaller } from "./components/AuthRedirectInstaller";
import { THEME_STORAGE_KEY } from "@/lib/theme";
import "katex/dist/katex.min.css";
import "@mescius/spread-sheets/styles/gc.spread.sheets.excel2013white.css";
@@ -41,6 +42,7 @@ export default function RootLayout({
+
{children}
diff --git a/src/lib/authRedirect.test.ts b/src/lib/authRedirect.test.ts
new file mode 100644
index 0000000..50b61fa
--- /dev/null
+++ b/src/lib/authRedirect.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { shouldRedirectFor } from "./authRedirect";
+
+describe("shouldRedirectFor", () => {
+ it("redirects on 401 for same-origin API paths", () => {
+ expect(shouldRedirectFor("/api/conversations", 401, "/")).toBe(true);
+ expect(
+ shouldRedirectFor("http://localhost/api/usage/summary", 401, "/chat")
+ ).toBe(true);
+ });
+
+ it("ignores non-401 statuses", () => {
+ expect(shouldRedirectFor("/api/conversations", 200, "/")).toBe(false);
+ expect(shouldRedirectFor("/api/conversations", 500, "/")).toBe(false);
+ });
+
+ it("ignores non-API paths", () => {
+ expect(shouldRedirectFor("/login", 401, "/")).toBe(false);
+ expect(shouldRedirectFor("/favicon.ico", 401, "/")).toBe(false);
+ });
+
+ it("ignores the login endpoint itself", () => {
+ expect(shouldRedirectFor("/api/auth/login", 401, "/login")).toBe(false);
+ expect(shouldRedirectFor("/api/auth/login", 401, "/")).toBe(false);
+ });
+
+ it("ignores 401 while already on the login page", () => {
+ expect(shouldRedirectFor("/api/auth/me", 401, "/login")).toBe(false);
+ });
+
+ it("ignores unparseable urls", () => {
+ expect(shouldRedirectFor("http://[", 401, "/")).toBe(false);
+ });
+});
diff --git a/src/lib/authRedirect.ts b/src/lib/authRedirect.ts
new file mode 100644
index 0000000..a1f03e5
--- /dev/null
+++ b/src/lib/authRedirect.ts
@@ -0,0 +1,53 @@
+export function shouldRedirectFor(
+ url: string,
+ status: number,
+ pathname: string
+): boolean {
+ if (status !== 401) return false;
+ if (pathname.startsWith("/login")) return false;
+ let path: string;
+ try {
+ path = new URL(url, "http://localhost").pathname;
+ } catch {
+ return false;
+ }
+ if (!path.startsWith("/api/")) return false;
+ if (path === "/api/auth/login") return false;
+ return true;
+}
+
+// Wraps window.fetch so any same-origin API 401 sends the browser to the
+// login page, preserving the current location as ?next. Returns a restore
+// function. Middleware only covers document navigations; fetch calls
+// (health checks, chat, polling) would otherwise fail silently as "offline".
+export function installAuthRedirect(): () => void {
+ const original = window.fetch;
+ const wrapped: typeof window.fetch = async (input, init) => {
+ const response = await original(input, init);
+ try {
+ const url =
+ typeof input === "string"
+ ? input
+ : input instanceof Request
+ ? input.url
+ : input.toString();
+ const resolved = new URL(url, window.location.origin);
+ if (
+ resolved.origin === window.location.origin &&
+ shouldRedirectFor(url, response.status, window.location.pathname)
+ ) {
+ const next = encodeURIComponent(
+ window.location.pathname + window.location.search
+ );
+ window.location.replace(`/login?next=${next}`);
+ }
+ } catch {
+ // Redirect failures must not break the caller's response handling.
+ }
+ return response;
+ };
+ window.fetch = wrapped;
+ return () => {
+ window.fetch = original;
+ };
+}