Skip to content

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

Fix LAN access: replace localhost with browser hostname at runtime (#340)

Zakir Jiwani21aef5830a22
diff --git a/web/lib/api.ts b/web/lib/api.ts
index a7d7ddd89..90b644452 100644
--- a/web/lib/api.ts
+++ b/web/lib/api.ts
@@ -17,6 +17,35 @@ export const API_BASE_URL =
);
})();
+/**
+ * Resolve the effective API base URL at runtime.
+ *
+ * NEXT_PUBLIC_API_BASE is a build-time constant that is typically set to
+ * http://localhost:<port>. When another machine on the LAN opens the app that
+ * constant still points at "localhost", which the remote browser resolves to
+ * its *own* loopback address instead of the server. We detect this situation
+ * and swap the hostname for window.location.hostname so the request reaches
+ * the actual server regardless of which machine opened the page.
+ */
+function resolveBase(): string {
+ const base = API_BASE_URL;
+ if (typeof window === "undefined") return base;
+ try {
+ const url = new URL(base);
+ const isLoopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
+ const clientIsRemote =
+ window.location.hostname !== "localhost" &&
+ window.location.hostname !== "127.0.0.1";
+ if (isLoopback && clientIsRemote) {
+ url.hostname = window.location.hostname;
+ return url.origin;
+ }
+ } catch {
+ // base is not a valid absolute URL – return as-is
+ }
+ return base;
+}
+
/**
* Construct a full API URL from a path
* @param path - API path (e.g., '/api/v1/knowledge/list')
@@ -27,11 +56,10 @@ export function apiUrl(path: string): string {
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
// Remove trailing slash from base URL if present
- const base = API_BASE_URL.endsWith("/")
- ? API_BASE_URL.slice(0, -1)
- : API_BASE_URL;
+ const base = resolveBase();
+ const normalizedBase = base.endsWith("/") ? base.slice(0, -1) : base;
- return `${base}${normalizedPath}`;
+ return `${normalizedBase}${normalizedPath}`;
}
/**
@@ -42,7 +70,7 @@ export function apiUrl(path: string): string {
export function wsUrl(path: string): string {
// Security Hardening: Convert http to ws and https to wss.
// In production environments (where API_BASE_URL starts with https), this ensures secure websockets.
- const base = API_BASE_URL.replace(/^http:/, "ws:").replace(/^https:/, "wss:");
+ const base = resolveBase().replace(/^http:/, "ws:").replace(/^https:/, "wss:");
// Remove leading slash if present to avoid double slashes
const normalizedPath = path.startsWith("/") ? path : `/${path}`;