π OpenHands: AI-Driven Development
chore(frontend): Change the backend base url fallback to be dynamic to current host (#4284)
sp.wackfe084b4b1676
diff --git a/frontend/src/api/open-hands.ts b/frontend/src/api/open-hands.tsindex c881b70a38..770385b5ec 100644--- a/frontend/src/api/open-hands.ts+++ b/frontend/src/api/open-hands.ts@@ -1,3 +1,4 @@+import { getValidFallbackHost } from "#/utils/get-valid-fallback-host";import {SaveFileSuccessResponse,FileUploadSuccessResponse,@@ -12,7 +13,9 @@ import {* @returns Base URL of the OpenHands API*/const generateBaseURL = () => {- const baseUrl = import.meta.env.VITE_BACKEND_BASE_URL || "localhost:3000";+ const fallback = getValidFallbackHost();+ const baseUrl = import.meta.env.VITE_BACKEND_BASE_URL || fallback;+return `http://${baseUrl}`;};diff --git a/frontend/src/context/socket.tsx b/frontend/src/context/socket.tsxindex 723a6478b9..8c820cca57 100644--- a/frontend/src/context/socket.tsx+++ b/frontend/src/context/socket.tsx@@ -1,6 +1,7 @@import React from "react";import { Data } from "ws";import EventLogger from "#/utils/event-logger";+import { getValidFallbackHost } from "#/utils/get-valid-fallback-host";interface WebSocketClientOptions {token: string | null;@@ -45,7 +46,8 @@ function SocketProvider({ children }: SocketProviderProps) {);}- const baseUrl = import.meta.env.VITE_BACKEND_BASE_URL || "localhost:3000";+ const fallback = getValidFallbackHost();+ const baseUrl = import.meta.env.VITE_BACKEND_BASE_URL || fallback;const ws = new WebSocket(`ws://${baseUrl}/ws${options?.token ? `?token=${options.token}` : ""}`,);diff --git a/frontend/src/utils/get-valid-fallback-host.ts b/frontend/src/utils/get-valid-fallback-host.tsnew file mode 100644index 0000000000..4b9c85b06e--- /dev/null+++ b/frontend/src/utils/get-valid-fallback-host.ts@@ -0,0 +1,20 @@+/**+ * Get the valid fallback host. Returns the host unless it is localhost, in which case it returns localhost:3000+ * @returns Valid fallback host+ *+ * @example+ * // If the host is localhost (e.g., localhost:5173), it returns localhost:3000+ * const host = getValidFallbackHost(); // localhost:3000+ *+ * // If the host is not localhost, it returns the host+ * const host = getValidFallbackHost(); // sub.example.com+ */+export const getValidFallbackHost = () => {+ if (typeof window !== "undefined") {+ const { hostname, host } = window.location;+ if (hostname !== "localhost") return host;+ }++ // Fallback is localhost:3000 because that is the default port for the server+ return "localhost:3000";+};