Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

fix: surface bad-login error inline instead of silent page reload

Ilia Avdeev79c160c3244a
diff --git a/web/lib/api.ts b/web/lib/api.ts
index 403905f1d..d1cf23681 100644
--- a/web/lib/api.ts
+++ b/web/lib/api.ts
@@ -136,14 +136,25 @@ const AUTH_ENABLED = process.env.NEXT_PUBLIC_AUTH_ENABLED === "true";
/**
* Authenticated fetch wrapper. Behaves identically to `fetch` but automatically
* redirects to /login when the backend returns 401 (expired / invalid token).
+ *
+ * Pass `skipAuthRedirect: true` for endpoints where a 401 is an expected,
+ * recoverable response that the caller wants to handle inline — most notably
+ * the login/register endpoints, where 401 means "wrong credentials" and must
+ * surface as a form error rather than reload the page.
*/
export async function apiFetch(
input: RequestInfo | URL,
- init?: RequestInit,
+ init?: RequestInit & { skipAuthRedirect?: boolean },
): Promise<Response> {
- const res = await fetch(input, { credentials: "include", ...init });
-
- if (res.status === 401 && AUTH_ENABLED && typeof window !== "undefined") {
+ const { skipAuthRedirect, ...fetchInit } = init ?? {};
+ const res = await fetch(input, { credentials: "include", ...fetchInit });
+
+ if (
+ res.status === 401 &&
+ AUTH_ENABLED &&
+ !skipAuthRedirect &&
+ typeof window !== "undefined"
+ ) {
const next = encodeURIComponent(window.location.pathname);
window.location.href = `/login?next=${next}`;
return new Promise(() => {});
diff --git a/web/lib/auth.ts b/web/lib/auth.ts
index 4c42868b1..103fe1891 100644
--- a/web/lib/auth.ts
+++ b/web/lib/auth.ts
@@ -37,6 +37,9 @@ export async function login(
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
+ // A 401 here means "wrong credentials", not an expired session — handle it
+ // inline as a form error instead of triggering the global login redirect.
+ skipAuthRedirect: true,
});
if (res.ok) return { ok: true };
@@ -80,6 +83,9 @@ export async function register(
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
+ // Registration validation failures (e.g. 400/401) should surface inline
+ // rather than bounce the user through the global login redirect.
+ skipAuthRedirect: true,
});
const data = await res.json().catch(() => ({}));