Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

feat: move all frontend calls to axios, add base path on frontend build (#2466)

Lucas Oliveirafca38c23d03c
diff --git a/.env.example b/.env.example
index d02a193a3..3dcc119ed 100644
--- a/.env.example
+++ b/.env.example
@@ -56,6 +56,11 @@ NUDGES_FLOW_ID=ebc01d31-1976-46ce-a385-b0240327226c
# Backend bind port for local `make backend`.
OPENRAG_BACKEND_PORT=8000
+# Optional path prefix used when serving the complete Next.js frontend below a
+# sub-path (for example https://example.com/openrag-fe). This is read when the
+# frontend is built, not when its container starts.
+# OPENRAG_FRONTEND_BASE_PATH=/openrag-fe
+
# URL Docker-hosted services use to call the backend in host-backend mode.
# If unset, auto-derived from OPENRAG_BACKEND_PORT. Only set this explicitly
# if you need to override the auto-derived value (e.g., custom hostname).
diff --git a/Dockerfile.frontend b/Dockerfile.frontend
index 6ec7f193d..7046dd386 100644
--- a/Dockerfile.frontend
+++ b/Dockerfile.frontend
@@ -26,6 +26,11 @@ FROM registry.access.redhat.com/ubi10/nodejs-24-minimal AS builder
WORKDIR /opt/app-root/src
USER 0
+# Next.js inlines basePath into browser bundles, so it has to be supplied when
+# this image is built rather than only at container runtime.
+ARG OPENRAG_FRONTEND_BASE_PATH
+ENV OPENRAG_FRONTEND_BASE_PATH=${OPENRAG_FRONTEND_BASE_PATH}
+
COPY --from=deps /opt/app-root/src/node_modules ./node_modules
COPY --from=deps /opt/app-root/src/stubs ./stubs
COPY frontend/package*.json ./
@@ -42,11 +47,17 @@ FROM registry.access.redhat.com/ubi10/nodejs-24-minimal AS runtime
WORKDIR /opt/app-root/src
USER 0
+# Next.js evaluates next.config.ts again when `next start` launches. Keep the
+# same build-time base path available in the runtime stage so the server-side
+# config agrees with the paths compiled into `.next`.
+ARG OPENRAG_FRONTEND_BASE_PATH
+
RUN microdnf update -y && microdnf clean all && rm -rf /var/cache/yum
ENV NODE_ENV=production \
- NEXT_TELEMETRY_DISABLED=1
+ NEXT_TELEMETRY_DISABLED=1 \
+ OPENRAG_FRONTEND_BASE_PATH=${OPENRAG_FRONTEND_BASE_PATH}
# CWE-426 fix: explicitly set PATH so system-owned directories are always resolved
# first. App venv dirs are appended last so they cannot shadow system binaries.
@@ -67,4 +78,4 @@ COPY --from=builder --chown=1001:0 /opt/app-root/src/biome.json* ./
EXPOSE 3000 9090
USER 1001
-CMD ["npm", "start"]
\ No newline at end of file
+CMD ["npm", "start"]
diff --git a/Makefile b/Makefile
index 37337061c..ccb06aa7a 100644
--- a/Makefile
+++ b/Makefile
@@ -24,6 +24,13 @@ REPO ?= https://github.com/langflow-ai/langflow.git
# Auto-detect container runtime: prefer docker, fall back to podman
CONTAINER_RUNTIME := $(shell command -v docker >/dev/null 2>&1 && echo "docker" || echo "podman")
+# Next.js compiles `basePath` into the frontend bundle, so every direct
+# frontend image build and local URL must use its normalized form.
+strip_trailing_slashes = $(if $(filter %/,$(1)),$(call strip_trailing_slashes,$(patsubst %/,%,$(1))),$(1))
+FRONTEND_NORMALIZED_BASE_PATH := $(call strip_trailing_slashes,$(strip $(OPENRAG_FRONTEND_BASE_PATH)))
+FRONTEND_NORMALIZED_BASE_PATH := $(if $(FRONTEND_NORMALIZED_BASE_PATH),$(if $(filter /%,$(FRONTEND_NORMALIZED_BASE_PATH)),$(FRONTEND_NORMALIZED_BASE_PATH),/$(FRONTEND_NORMALIZED_BASE_PATH)))
+FRONTEND_BASE_PATH_BUILD_ARG := --build-arg OPENRAG_FRONTEND_BASE_PATH="$(FRONTEND_NORMALIZED_BASE_PATH)"
+FRONTEND_LOCAL_URL := http://localhost:3000$(FRONTEND_NORMALIZED_BASE_PATH)
# Host UID/GID — evaluated once at parse time and used in Docker-assisted chown commands
# so that Alpine (running as root) can re-own volume directories back to the host user.
@@ -935,7 +942,7 @@ build-be: ## Build backend Docker image
build-fe: ## Build frontend Docker image
@echo "$(YELLOW)Building frontend image...$(NC)"
- $(CONTAINER_RUNTIME) build -t langflowai/openrag-frontend:latest -f Dockerfile.frontend .
+ $(CONTAINER_RUNTIME) build $(FRONTEND_BASE_PATH_BUILD_ARG) -t langflowai/openrag-frontend:latest -f Dockerfile.frontend .
@echo "$(PURPLE)Frontend image built.$(NC)"
build-lf: ## Build Langflow Docker image
@@ -1026,7 +1033,7 @@ ci-build-images: ## Build all OpenRAG images for CI artifact sharing
echo "$(YELLOW)Building all OpenRAG images with tag '$$IMAGE_TAG'...$(NC)"; \
$(CONTAINER_RUNTIME) build -t langflowai/openrag-opensearch:$$IMAGE_TAG -f Dockerfile .; \
$(CONTAINER_RUNTIME) build -t langflowai/openrag-backend:$$IMAGE_TAG -f Dockerfile.backend .; \
- $(CONTAINER_RUNTIME) build -t langflowai/openrag-frontend:$$IMAGE_TAG -f Dockerfile.frontend .; \
+ $(CONTAINER_RUNTIME) build $(FRONTEND_BASE_PATH_BUILD_ARG) -t langflowai/openrag-frontend:$$IMAGE_TAG -f Dockerfile.frontend .; \
$(CONTAINER_RUNTIME) build -t langflowai/openrag-langflow:$$IMAGE_TAG -f Dockerfile.langflow .; \
echo "$(GREEN)All images built successfully!$(NC)"
@@ -1141,9 +1148,9 @@ test-ci: ensure-langflow-data ensure-backend-volumes ## Start infra, run integra
uv run pytest tests/integration/core -vv -s --log-file=service-logs/pytest-core.log --log-file-level=DEBUG --junitxml=service-logs/junit-core.xml || TEST_RESULT=1; \
echo "::endgroup::"; \
echo ""; \
- echo "$(YELLOW)Waiting for frontend at http://localhost:3000...$(NC)"; \
+ echo "$(YELLOW)Waiting for frontend at $(FRONTEND_LOCAL_URL)...$(NC)"; \
for i in $$(seq 1 60); do \
- curl -s http://localhost:3000/ >/dev/null 2>&1 && break || sleep 2; \
+ curl -s $(FRONTEND_LOCAL_URL)/ >/dev/null 2>&1 && break || sleep 2; \
done; \
echo "::group::SDK Integration Tests (Python)"; \
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
@@ -1151,7 +1158,7 @@ test-ci: ensure-langflow-data ensure-backend-volumes ## Start infra, run integra
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
uv pip install --quiet -e sdks/python; \
mkdir -p service-logs; \
- SDK_TESTS_ONLY=true OPENRAG_URL=http://localhost:3000 uv run pytest tests/integration/sdk/ -vv -s --log-file=service-logs/pytest-sdk.log --log-file-level=DEBUG --junitxml=service-logs/junit-sdk-python.xml || TEST_RESULT=1; \
+ SDK_TESTS_ONLY=true OPENRAG_URL=$(FRONTEND_LOCAL_URL) uv run pytest tests/integration/sdk/ -vv -s --log-file=service-logs/pytest-sdk.log --log-file-level=DEBUG --junitxml=service-logs/junit-sdk-python.xml || TEST_RESULT=1; \
echo "::endgroup::"; \
echo "::group::SDK Integration Tests (TypeScript)"; \
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
@@ -1159,7 +1166,7 @@ test-ci: ensure-langflow-data ensure-backend-volumes ## Start infra, run integra
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
cd sdks/typescript && \
npm install && npm run build && \
- OPENRAG_URL=http://localhost:3000 npm test -- --reporter=junit --outputFile=../../service-logs/junit-sdk-typescript.xml || TEST_RESULT=1; \
+ OPENRAG_URL=$(FRONTEND_LOCAL_URL) npm test -- --reporter=junit --outputFile=../../service-logs/junit-sdk-typescript.xml || TEST_RESULT=1; \
cd ../..; \
echo "::endgroup::"; \
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
@@ -1184,7 +1191,7 @@ test-ci-local: ensure-langflow-data ensure-backend-volumes ## Same as test-ci bu
echo "$(YELLOW)Building all images locally...$(NC)"; \
$(CONTAINER_RUNTIME) build -t langflowai/openrag-opensearch:latest -f Dockerfile .; \
$(CONTAINER_RUNTIME) build -t langflowai/openrag-backend:latest -f Dockerfile.backend .; \
- $(CONTAINER_RUNTIME) build -t langflowai/openrag-frontend:latest -f Dockerfile.frontend .; \
+ $(CONTAINER_RUNTIME) build $(FRONTEND_BASE_PATH_BUILD_ARG) -t langflowai/openrag-frontend:latest -f Dockerfile.frontend .; \
$(CONTAINER_RUNTIME) build -t langflowai/openrag-langflow:latest -f Dockerfile.langflow .; \
echo "::endgroup::"; \
echo "::group::Start Infrastructure"; \
@@ -1270,9 +1277,9 @@ test-ci-local: ensure-langflow-data ensure-backend-volumes ## Same as test-ci bu
uv run pytest tests/integration/core -vv -s --log-file=service-logs/pytest-core.log --log-file-level=DEBUG --junitxml=service-logs/junit-core.xml || TEST_RESULT=1; \
echo "::endgroup::"; \
echo ""; \
- echo "$(YELLOW)Waiting for frontend at http://localhost:3000...$(NC)"; \
+ echo "$(YELLOW)Waiting for frontend at $(FRONTEND_LOCAL_URL)...$(NC)"; \
for i in $$(seq 1 60); do \
- curl -s http://localhost:3000/ >/dev/null 2>&1 && break || sleep 2; \
+ curl -s $(FRONTEND_LOCAL_URL)/ >/dev/null 2>&1 && break || sleep 2; \
done; \
echo "::group::SDK Integration Tests (Python)"; \
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
@@ -1280,7 +1287,7 @@ test-ci-local: ensure-langflow-data ensure-backend-volumes ## Same as test-ci bu
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
uv pip install --quiet -e sdks/python; \
mkdir -p service-logs; \
- SDK_TESTS_ONLY=true OPENRAG_URL=http://localhost:3000 uv run pytest tests/integration/sdk/ -vv -s --log-file=service-logs/pytest-sdk.log --log-file-level=DEBUG --junitxml=service-logs/junit-sdk-python.xml || TEST_RESULT=1; \
+ SDK_TESTS_ONLY=true OPENRAG_URL=$(FRONTEND_LOCAL_URL) uv run pytest tests/integration/sdk/ -vv -s --log-file=service-logs/pytest-sdk.log --log-file-level=DEBUG --junitxml=service-logs/junit-sdk-python.xml || TEST_RESULT=1; \
echo "::endgroup::"; \
echo "::group::SDK Integration Tests (TypeScript)"; \
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
@@ -1288,7 +1295,7 @@ test-ci-local: ensure-langflow-data ensure-backend-volumes ## Same as test-ci bu
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
cd sdks/typescript && \
npm install && npm run build && \
- OPENRAG_URL=http://localhost:3000 npm test -- --reporter=junit --outputFile=../../service-logs/junit-sdk-typescript.xml || TEST_RESULT=1; \
+ OPENRAG_URL=$(FRONTEND_LOCAL_URL) npm test -- --reporter=junit --outputFile=../../service-logs/junit-sdk-typescript.xml || TEST_RESULT=1; \
cd ../..; \
echo "::endgroup::"; \
echo "$(CYAN)════════════════════════════════════════$(NC)"; \
@@ -1320,10 +1327,10 @@ test-sdk: ## Run SDK integration tests (requires running OpenRAG at localhost:30
@echo "$(CYAN)════════════════════════════════════════$(NC)"
@echo "$(YELLOW)Make sure OpenRAG is running at localhost:3000 (make dev)$(NC)"
uv pip install -e sdks/python
- SDK_TESTS_ONLY=true OPENRAG_URL=http://localhost:3000 uv run pytest tests/integration/sdk/ -vv -s
+ SDK_TESTS_ONLY=true OPENRAG_URL=$(FRONTEND_LOCAL_URL) uv run pytest tests/integration/sdk/ -vv -s
@echo ""
@echo "$(PURPLE)Running TypeScript SDK tests...$(NC)"
- cd sdks/typescript && npm install && npm run build && OPENRAG_URL=http://localhost:3000 npm test
+ cd sdks/typescript && npm install && npm run build && OPENRAG_URL=$(FRONTEND_LOCAL_URL) npm test
@echo "$(PURPLE)SDK tests complete.$(NC)"
lint: ## Run linting checks
@@ -1342,7 +1349,7 @@ status: ## Show container status
health: ## Check health of all services
@printf "$(PURPLE)Health check:$(NC)\n"
@printf "$(CYAN)Frontend:$(NC) "
- @if curl -s -k --fail http://127.0.0.1:$${FRONTEND_PORT:-3000}/ >/dev/null 2>&1; then printf "$(GREEN)Healthy$(NC)\n"; else printf "$(RED)Not responding$(NC)\n"; fi
+ @if curl -s -k --fail http://127.0.0.1:$${FRONTEND_PORT:-3000}$(OPENRAG_FRONTEND_BASE_PATH)/ >/dev/null 2>&1; then printf "$(GREEN)Healthy$(NC)\n"; else printf "$(RED)Not responding$(NC)\n"; fi
@printf "$(CYAN)Backend:$(NC) "
@if curl -s -k --fail http://127.0.0.1:$${OPENRAG_BACKEND_PORT:-8000}/health >/dev/null 2>&1; then \
printf "$(GREEN)Healthy$(NC)\n"; \
diff --git a/docker-compose.yml b/docker-compose.yml
index bbf2320a5..aba3fd087 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -197,6 +197,8 @@ services:
build:
context: .
dockerfile: Dockerfile.frontend
+ args:
+ OPENRAG_FRONTEND_BASE_PATH: ${OPENRAG_FRONTEND_BASE_PATH:-}
container_name: ${COMPOSE_PROJECT_NAME:-openrag}-frontend
depends_on:
- openrag-backend
diff --git a/docs/docs/reference/configuration.mdx b/docs/docs/reference/configuration.mdx
index e1bdc350c..e8ab24f34 100644
--- a/docs/docs/reference/configuration.mdx
+++ b/docs/docs/reference/configuration.mdx
@@ -353,6 +353,7 @@ Configure general system components, session management, and logging.
| Variable | Default | Description |
|----------|---------|-------------|
| `FRONTEND_PORT` | `3000` | Host port for the OpenRAG frontend web interface. Change this if port 3000 is already in use on your system. |
+| `OPENRAG_FRONTEND_BASE_PATH` | Not set | Optional URL path below which the complete frontend is served, such as `/openrag-fe`. This is a frontend **build-time** setting; rebuild the frontend image after changing it. |
| `OPENRAG_VERSION` | `latest` | The version of the OpenRAG Docker images to run. If [`OPENRAG_IMAGE_TAG`](#container-image-and-registry-settings) is set, it takes precedence over this variable. For more information, see [Upgrade OpenRAG](/upgrade) |
| `NEXT_ALLOWED_DEV_ORIGINS` | `http://localhost:3000` | Only used when [running OpenRAG in development mode](/support/contribute). Accepts a comma-separated list of hostnames to allow additional origins to make requests to the Next.js development server. |
| `MAX_WORKERS` | `min(4, CPU_COUNT // 2)` | Number of Backend worker processes for concurrent request handling. Be mindful of hardware limitations to avoid overtaxing system resources. |
diff --git a/frontend/app/api/mutations/useBulkDeleteSessionsMutation.ts b/frontend/app/api/mutations/useBulkDeleteSessionsMutation.ts
index 394ae8dfc..adba8193e 100644
--- a/frontend/app/api/mutations/useBulkDeleteSessionsMutation.ts
+++ b/frontend/app/api/mutations/useBulkDeleteSessionsMutation.ts
@@ -4,6 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import type { EndpointType } from "@/contexts/chat-context";
+import { apiClient } from "@/lib/api-client";
export interface BulkDeleteSessionsRequest {
session_ids: string[];
@@ -18,20 +19,21 @@ export interface BulkDeleteSessionsResponse {
async function bulkDeleteSessions(
variables: BulkDeleteSessionsRequest,
): Promise<BulkDeleteSessionsResponse> {
- const response = await fetch("/api/sessions", {
- method: "DELETE",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ session_ids: variables.session_ids }),
- });
+ const response = await apiClient.delete<BulkDeleteSessionsResponse>(
+ "/sessions",
+ {
+ data: { session_ids: variables.session_ids },
+ },
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data as unknown as { error?: string };
throw new Error(
errorData.error || `Failed to delete sessions: ${response.status}`,
);
}
- return response.json();
+ return response.data;
}
export const useBulkDeleteSessionsMutation = (
diff --git a/frontend/app/api/mutations/useCancelFileMutation.test.ts b/frontend/app/api/mutations/useCancelFileMutation.test.ts
index 0d4d94b77..457b706b7 100644
--- a/frontend/app/api/mutations/useCancelFileMutation.test.ts
+++ b/frontend/app/api/mutations/useCancelFileMutation.test.ts
@@ -1,20 +1,25 @@
import { renderHook, waitFor } from "@testing-library/react";
+import { HttpResponse, http } from "msw";
import { describe, expect, it, vi } from "vitest";
+import { server } from "@/test-utils/msw/server";
import { createQueryWrapper } from "@/test-utils/render";
import { useCancelFileMutation } from "./useCancelFileMutation";
describe("useCancelFileMutation", () => {
it("calls the cancel file API endpoint with correct parameters", async () => {
- global.fetch = vi.fn(() =>
- Promise.resolve({
- ok: true,
- json: () =>
- Promise.resolve({
+ const seen = vi.fn();
+ server.use(
+ http.post(
+ "/api/tasks/test-task-123/files/cancel",
+ async ({ request }) => {
+ seen(await request.json());
+ return HttpResponse.json({
status: "cancelled",
task_id: "test-task-123",
file_path: "test.pdf",
- }),
- } as Response),
+ });
+ },
+ ),
);
const { result } = renderHook(() => useCancelFileMutation(), {
@@ -24,23 +29,17 @@ describe("useCancelFileMutation", () => {
result.current.mutate({ taskId: "test-task-123", filePath: "test.pdf" });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
- expect(global.fetch).toHaveBeenCalledWith(
- "/api/tasks/test-task-123/files/cancel",
- expect.objectContaining({
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ file_path: "test.pdf" }),
- }),
- );
+ expect(seen).toHaveBeenCalledWith({ file_path: "test.pdf" });
});
it("handles error when file cannot be cancelled", async () => {
- global.fetch = vi.fn(() =>
- Promise.resolve({
- ok: false,
- json: () =>
- Promise.resolve({ error: "File not found or cannot be cancelled" }),
- } as Response),
+ server.use(
+ http.post("/api/tasks/test-task-123/files/cancel", () =>
+ HttpResponse.json(
+ { error: "File not found or cannot be cancelled" },
+ { status: 404 },
+ ),
+ ),
);
const { result } = renderHook(() => useCancelFileMutation(), {
@@ -56,11 +55,11 @@ describe("useCancelFileMutation", () => {
});
it("handles network errors gracefully", async () => {
- global.fetch = vi.fn(() =>
- Promise.resolve({
- ok: false,
- json: () => Promise.reject(new Error("Network error")),
- } as Response),
+ server.use(
+ http.post(
+ "/api/tasks/test-task-123/files/cancel",
+ () => new HttpResponse("not JSON", { status: 500 }),
+ ),
);
const { result } = renderHook(() => useCancelFileMutation(), {
diff --git a/frontend/app/api/mutations/useCancelFileMutation.ts b/frontend/app/api/mutations/useCancelFileMutation.ts
index 447885d5a..62361073a 100644
--- a/frontend/app/api/mutations/useCancelFileMutation.ts
+++ b/frontend/app/api/mutations/useCancelFileMutation.ts
@@ -5,6 +5,7 @@ import {
} from "@tanstack/react-query";
import { taskDetailQueryKey } from "@/app/api/queries/useGetTaskQuery";
import { TASKS_QUERY_KEY } from "@/app/api/queries/useGetTasksQuery";
+import { apiClient } from "@/lib/api-client";
export interface CancelFileRequest {
taskId: string;
@@ -20,22 +21,17 @@ export interface CancelFileResponse {
async function cancelFile(
variables: CancelFileRequest,
): Promise<CancelFileResponse> {
- const response = await fetch(`/api/tasks/${variables.taskId}/files/cancel`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- file_path: variables.filePath,
- }),
- });
+ const response = await apiClient.post<CancelFileResponse>(
+ `/tasks/${variables.taskId}/files/cancel`,
+ { file_path: variables.filePath },
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data as unknown as { error?: string };
throw new Error(errorData.error || "Failed to cancel file");
}
- return response.json();
+ return response.data;
}
export const useCancelFileMutation = (
diff --git a/frontend/app/api/mutations/useCancelTaskMutation.ts b/frontend/app/api/mutations/useCancelTaskMutation.ts
index 5727422b6..46130895e 100644
--- a/frontend/app/api/mutations/useCancelTaskMutation.ts
+++ b/frontend/app/api/mutations/useCancelTaskMutation.ts
@@ -5,6 +5,7 @@ import {
} from "@tanstack/react-query";
import { taskDetailQueryKey } from "@/app/api/queries/useGetTaskQuery";
import { TASKS_QUERY_KEY } from "@/app/api/queries/useGetTasksQuery";
+import { apiClient } from "@/lib/api-client";
export interface CancelTaskRequest {
taskId: string;
@@ -18,16 +19,16 @@ export interface CancelTaskResponse {
async function cancelTask(
variables: CancelTaskRequest,
): Promise<CancelTaskResponse> {
- const response = await fetch(`/api/tasks/${variables.taskId}/cancel`, {
- method: "POST",
- });
+ const response = await apiClient.post<CancelTaskResponse>(
+ `/tasks/${variables.taskId}/cancel`,
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data as unknown as { error?: string };
throw new Error(errorData.error || "Failed to cancel task");
}
- return response.json();
+ return response.data;
}
export const useCancelTaskMutation = (
diff --git a/frontend/app/api/mutations/useConnectConnectorMutation.ts b/frontend/app/api/mutations/useConnectConnectorMutation.ts
index 40e653cba..768e1dafc 100644
--- a/frontend/app/api/mutations/useConnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useConnectConnectorMutation.ts
@@ -1,6 +1,8 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
import { useAuth } from "@/contexts/auth-context";
+import { apiClient } from "@/lib/api-client";
+import { frontendUrl } from "@/lib/frontend-base-path";
import { encodeBase64 } from "@/lib/utils";
import type {
Connector,
@@ -39,26 +41,20 @@ export const useConnectConnectorMutation = () => {
* not persist a data-source connection on success. */
purpose?: "data_source" | "test";
}): Promise<ConnectResponse> => {
- const response = await fetch("/api/auth/init", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- connector_type: connector.type,
- purpose,
- name: `${connector.name} Connection`,
- redirect_uri: redirectUri,
- }),
+ const response = await apiClient.post("/auth/init", {
+ connector_type: connector.type,
+ purpose,
+ name: `${connector.name} Connection`,
+ redirect_uri: redirectUri,
});
- if (!response.ok) {
- const result = await response.json();
+ if (response.status < 200 || response.status >= 300) {
+ const result = response.data;
throw new Error(
result.error || `Failed to initiate connection for ${connector.name}`,
);
}
- return response.json();
+ return response.data;
},
onMutate: async (): Promise<ConnectorsMutationContext> => {
await queryClient.cancelQueries(connectorsQueryFilter);
@@ -84,7 +80,7 @@ export const useConnectConnectorMutation = () => {
const state = isIbmAuthMode
? encodeBase64(
- `id=${result.connection_id}&return=${window.location.origin}/auth/callback`,
+ `id=${result.connection_id}&return=${frontendUrl("/auth/callback")}`,
)
: result.connection_id;
diff --git a/frontend/app/api/mutations/useConnectorOAuthConfigMutation.ts b/frontend/app/api/mutations/useConnectorOAuthConfigMutation.ts
index 2319bdaad..6f86f55b4 100644
--- a/frontend/app/api/mutations/useConnectorOAuthConfigMutation.ts
+++ b/frontend/app/api/mutations/useConnectorOAuthConfigMutation.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import { connectorOAuthConfigQueryKey } from "../queries/useConnectorOAuthConfigQuery";
export interface SaveConnectorOAuthConfigPayload {
@@ -12,16 +13,12 @@ async function saveConnectorOAuthConfig({
client_id,
client_secret,
}: SaveConnectorOAuthConfigPayload) {
- const res = await fetch(
- `/api/connectors/oauth-config/${encodeURIComponent(credentialKey)}`,
- {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ client_id, client_secret }),
- },
+ const res = await apiClient.put(
+ `/connectors/oauth-config/${encodeURIComponent(credentialKey)}`,
+ { client_id, client_secret },
);
- const data = await res.json();
- if (!res.ok)
+ const data = res.data ?? {};
+ if (res.status < 200 || res.status >= 300)
throw new Error(data.error || "Failed to save connector credentials");
return data;
}
@@ -38,12 +35,11 @@ export function useSaveConnectorOAuthConfigMutation() {
}
async function clearConnectorOAuthConfig(credentialKey: string) {
- const res = await fetch(
- `/api/connectors/oauth-config/${encodeURIComponent(credentialKey)}`,
- { method: "DELETE" },
+ const res = await apiClient.delete(
+ `/connectors/oauth-config/${encodeURIComponent(credentialKey)}`,
);
- const data = await res.json();
- if (!res.ok)
+ const data = res.data ?? {};
+ if (res.status < 200 || res.status >= 300)
throw new Error(data.error || "Failed to clear connector credentials");
return data;
}
diff --git a/frontend/app/api/mutations/useCreateApiKeyMutation.ts b/frontend/app/api/mutations/useCreateApiKeyMutation.ts
index 9caed9477..fc829cf7d 100644
--- a/frontend/app/api/mutations/useCreateApiKeyMutation.ts
+++ b/frontend/app/api/mutations/useCreateApiKeyMutation.ts
@@ -3,6 +3,7 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface CreateApiKeyRequest {
name: string;
@@ -19,20 +20,17 @@ export interface CreateApiKeyResponse {
async function createApiKey(
variables: CreateApiKeyRequest,
): Promise<CreateApiKeyResponse> {
- const response = await fetch("/api/keys", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(variables),
- });
+ const response = await apiClient.post<CreateApiKeyResponse>(
+ "/keys",
+ variables,
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data as unknown as { error?: string };
throw new Error(errorData.error || "Failed to create API key");
}
- return response.json();
+ return response.data;
}
export const useCreateApiKeyMutation = (
diff --git a/frontend/app/api/mutations/useCreateFilter.ts b/frontend/app/api/mutations/useCreateFilter.ts
index db86dfd46..3f861c57d 100644
--- a/frontend/app/api/mutations/useCreateFilter.ts
+++ b/frontend/app/api/mutations/useCreateFilter.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import { KnowledgeFilter } from "../queries/useGetFiltersSearchQuery";
export interface CreateFilterRequest {
@@ -16,27 +17,23 @@ export interface CreateFilterResponse {
async function createFilter(
data: CreateFilterRequest,
): Promise<CreateFilterResponse> {
- const response = await fetch("/api/knowledge-filter", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
+ const response = await apiClient.post<CreateFilterResponse>(
+ "/knowledge-filter",
+ {
name: data.name,
description: data.description ?? "",
queryData: data.queryData,
- }),
- });
-
- const json = await response.json().catch(() => ({}));
+ },
+ );
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
const errorMessage =
- (json && (json.error as string)) || "Failed to create knowledge filter";
+ (response.data as { error?: string }).error ||
+ "Failed to create knowledge filter";
throw new Error(errorMessage);
}
- return json as CreateFilterResponse;
+ return response.data;
}
export const useCreateFilter = () => {
diff --git a/frontend/app/api/mutations/useDeleteDocument.ts b/frontend/app/api/mutations/useDeleteDocument.ts
index adea15b03..4f0edf137 100644
--- a/frontend/app/api/mutations/useDeleteDocument.ts
+++ b/frontend/app/api/mutations/useDeleteDocument.ts
@@ -1,6 +1,7 @@
"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
interface DeleteDocumentRequest {
filename: string;
@@ -16,20 +17,17 @@ interface DeleteDocumentResponse {
async function deleteDocumentByFilename(
filename: string,
): Promise<DeleteDocumentResponse> {
- const response = await fetch("/api/documents/delete-by-filename", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ filename } satisfies DeleteDocumentRequest),
- });
+ const response = await apiClient.post<DeleteDocumentResponse>(
+ "/documents/delete-by-filename",
+ { filename } satisfies DeleteDocumentRequest,
+ );
- if (!response.ok) {
- const error = await response.json();
+ if (response.status < 200 || response.status >= 300) {
+ const error = response.data as unknown as { error?: string };
throw new Error(error.error || "Failed to delete document");
}
- return response.json();
+ return response.data;
}
export const useDeleteDocument = () => {
diff --git a/frontend/app/api/mutations/useDeleteFilter.ts b/frontend/app/api/mutations/useDeleteFilter.ts
index 85abe9c36..a18df0ab3 100644
--- a/frontend/app/api/mutations/useDeleteFilter.ts
+++ b/frontend/app/api/mutations/useDeleteFilter.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface DeleteFilterRequest {
id: string;
@@ -12,19 +13,18 @@ export interface DeleteFilterResponse {
async function deleteFilter(
data: DeleteFilterRequest,
): Promise<DeleteFilterResponse> {
- const response = await fetch(`/api/knowledge-filter/${data.id}`, {
- method: "DELETE",
- });
-
- const json = await response.json().catch(() => ({}));
+ const response = await apiClient.delete<DeleteFilterResponse>(
+ `/knowledge-filter/${data.id}`,
+ );
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
const errorMessage =
- (json && (json.error as string)) || "Failed to delete knowledge filter";
+ (response.data as { error?: string }).error ||
+ "Failed to delete knowledge filter";
throw new Error(errorMessage);
}
- return (json as DeleteFilterResponse) || { success: true };
+ return response.data || { success: true };
}
export const useDeleteFilter = () => {
diff --git a/frontend/app/api/mutations/useDeleteTaskMutation.ts b/frontend/app/api/mutations/useDeleteTaskMutation.ts
index 149b51541..297e8d54b 100644
--- a/frontend/app/api/mutations/useDeleteTaskMutation.ts
+++ b/frontend/app/api/mutations/useDeleteTaskMutation.ts
@@ -1,14 +1,15 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { TASKS_QUERY_KEY, type Task } from "@/app/api/queries/useGetTasksQuery";
+import { apiClient } from "@/lib/api-client";
export function useDeleteTaskMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (taskId: string) => {
- const res = await fetch(`/api/tasks/${taskId}`, { method: "DELETE" });
+ const res = await apiClient.delete(`/tasks/${taskId}`);
if (res.status === 404) return;
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
+ if (res.status < 200 || res.status >= 300) {
+ const body = res.data;
throw new Error(
(body as { error?: string }).error ?? "Failed to delete task",
);
@@ -29,15 +30,15 @@ export function useDeleteAllTerminalTasksMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (): Promise<string[]> => {
- const res = await fetch("/api/tasks", { method: "DELETE" });
+ const res = await apiClient.delete<{ deleted_ids?: unknown }>("/tasks");
if (res.status === 404) return [];
- if (!res.ok) {
- const body = await res.json().catch(() => ({}));
+ if (res.status < 200 || res.status >= 300) {
+ const body = res.data;
throw new Error(
(body as { error?: string }).error ?? "Failed to delete tasks",
);
}
- const body = await res.json();
+ const body = res.data;
if (
!Array.isArray(body.deleted_ids) ||
!body.deleted_ids.every((id: unknown) => typeof id === "string")
diff --git a/frontend/app/api/mutations/useDisconnectConnectorMutation.ts b/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
index 73676d2d0..9c4d7a69a 100644
--- a/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useDisconnectConnectorMutation.ts
@@ -1,5 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
+import { apiClient } from "@/lib/api-client";
import type {
Connector,
ConnectorsMutationContext,
@@ -16,20 +17,17 @@ export const useDisconnectConnectorMutation = () => {
return useMutation({
mutationFn: async (connector: Connector) => {
- const response = await fetch(
- `/api/connectors/${connector.type}/disconnect`,
- {
- method: "DELETE",
- },
+ const response = await apiClient.delete(
+ `/connectors/${connector.type}/disconnect`,
);
- if (!response.ok) {
- const result = await response.json();
+ if (response.status < 200 || response.status >= 300) {
+ const result = response.data ?? {};
throw new Error(
result.error || `Failed to disconnect ${connector.name}`,
);
}
- return response.json();
+ return response.data;
},
onMutate: async (connector): Promise<ConnectorsMutationContext> => {
await queryClient.cancelQueries(connectorsQueryFilter);
diff --git a/frontend/app/api/mutations/useDismissFlowsUpdateMutation.ts b/frontend/app/api/mutations/useDismissFlowsUpdateMutation.ts
index 878cd89ca..d86d3ee93 100644
--- a/frontend/app/api/mutations/useDismissFlowsUpdateMutation.ts
+++ b/frontend/app/api/mutations/useDismissFlowsUpdateMutation.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
interface DismissFlowsUpdateVariables {
flow_types?: string[];
@@ -9,18 +10,17 @@ export function useDismissFlowsUpdateMutation() {
return useMutation({
mutationFn: async (variables?: DismissFlowsUpdateVariables) => {
- const response = await fetch("/api/settings/flows/dismiss-update", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(variables || {}),
- });
+ const response = await apiClient.post(
+ "/settings/flows/dismiss-update",
+ variables || {},
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data as { error?: string };
throw new Error(errorData.error || "Failed to dismiss flow updates");
}
- return response.json();
+ return response.data;
},
onSuccess: () => {
queryClient.invalidateQueries({
diff --git a/frontend/app/api/mutations/useOnboardingMutation.ts b/frontend/app/api/mutations/useOnboardingMutation.ts
index c07a76c69..646db9402 100644
--- a/frontend/app/api/mutations/useOnboardingMutation.ts
+++ b/frontend/app/api/mutations/useOnboardingMutation.ts
@@ -4,6 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import { toast } from "sonner";
+import { apiClient } from "@/lib/api-client";
import { formatProviderErrorMessage } from "@/lib/chat-stream-errors";
import { useUpdateOnboardingStateMutation } from "./useUpdateOnboardingStateMutation";
@@ -39,16 +40,13 @@ interface OnboardingResponse {
async function submitOnboarding(
variables: OnboardingVariables,
): Promise<OnboardingResponse> {
- const response = await fetch("/api/onboarding", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(variables),
- });
+ const response = await apiClient.post<OnboardingResponse>(
+ "/onboarding",
+ variables,
+ );
- if (!response.ok) {
- const error = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const error = (response.data ?? {}) as unknown as Record<string, unknown>;
const raw =
error && typeof error === "object" && typeof error.error === "string"
? error.error
@@ -56,7 +54,7 @@ async function submitOnboarding(
throw new Error(formatProviderErrorMessage(raw));
}
- return response.json();
+ return response.data;
}
export const useOnboardingMutation = (
diff --git a/frontend/app/api/mutations/useOnboardingRollbackMutation.ts b/frontend/app/api/mutations/useOnboardingRollbackMutation.ts
index 127a9c982..789f723dd 100644
--- a/frontend/app/api/mutations/useOnboardingRollbackMutation.ts
+++ b/frontend/app/api/mutations/useOnboardingRollbackMutation.ts
@@ -3,6 +3,7 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
interface OnboardingRollbackResponse {
message: string;
@@ -19,25 +20,25 @@ async function rollbackOnboarding(
): Promise<OnboardingRollbackResponse> {
const requestBody = params || { embedding_only: false };
- const response = await fetch("/api/onboarding/rollback", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(requestBody),
- });
+ const response = await apiClient.post<OnboardingRollbackResponse>(
+ "/onboarding/rollback",
+ requestBody,
+ );
- if (!response.ok) {
- const text = await response.text();
+ if (response.status < 200 || response.status >= 300) {
+ const text = typeof response.data === "string" ? response.data : "";
let message = "Failed to rollback onboarding";
try {
- const error = JSON.parse(text);
+ const error =
+ response.data && typeof response.data === "object"
+ ? response.data
+ : JSON.parse(text);
if (error.error) message = error.error;
} catch {}
throw new Error(message);
}
- return response.json();
+ return response.data;
}
export const useOnboardingRollbackMutation = (
diff --git a/frontend/app/api/mutations/useRefreshOpenragDocs.ts b/frontend/app/api/mutations/useRefreshOpenragDocs.ts
index 5319428b6..78c2a37fa 100644
--- a/frontend/app/api/mutations/useRefreshOpenragDocs.ts
+++ b/frontend/app/api/mutations/useRefreshOpenragDocs.ts
@@ -1,6 +1,7 @@
"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
interface RefreshOpenRAGDocsResponse {
message: string;
@@ -8,26 +9,17 @@ interface RefreshOpenRAGDocsResponse {
}
const refreshOpenragDocs = async (): Promise<RefreshOpenRAGDocsResponse> => {
- const response = await fetch("/api/openrag-docs/refresh", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- });
+ const response = await apiClient.post<unknown>("/openrag-docs/refresh");
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
let errorMessage = "Failed to refresh OpenRAG docs";
try {
- const contentType = response.headers.get("content-type") || "";
- if (contentType.includes("application/json")) {
- const error = await response.json();
+ if (typeof response.data === "object" && response.data !== null) {
+ const error = response.data as { detail?: string; error?: string };
errorMessage = error.detail || error.error || errorMessage;
- } else {
- const text = (await response.text()).trim();
- if (text) {
- errorMessage = text;
- }
+ } else if (typeof response.data === "string" && response.data.trim()) {
+ errorMessage = response.data.trim();
}
} catch {
// Keep default fallback message for malformed/non-JSON bodies.
@@ -36,7 +28,7 @@ const refreshOpenragDocs = async (): Promise<RefreshOpenRAGDocsResponse> => {
throw new Error(errorMessage);
}
- return response.json();
+ return response.data as RefreshOpenRAGDocsResponse;
};
export const useRefreshOpenragDocs = () => {
diff --git a/frontend/app/api/mutations/useRetryTaskMutation.ts b/frontend/app/api/mutations/useRetryTaskMutation.ts
index cb0e7c060..070f1c8c5 100644
--- a/frontend/app/api/mutations/useRetryTaskMutation.ts
+++ b/frontend/app/api/mutations/useRetryTaskMutation.ts
@@ -5,6 +5,7 @@ import {
} from "@tanstack/react-query";
import { taskDetailQueryKey } from "@/app/api/queries/useGetTaskQuery";
import { TASKS_QUERY_KEY } from "@/app/api/queries/useGetTasksQuery";
+import { apiClient } from "@/lib/api-client";
export interface RetryTaskRequest {
taskId: string;
@@ -35,21 +36,13 @@ export interface RetryTaskResponse {
async function retryTask(
variables: RetryTaskRequest,
): Promise<RetryTaskResponse> {
- const body = JSON.stringify(
+ const response = await apiClient.post<RetryTaskResponse>(
+ `/tasks/${variables.taskId}/retry`,
variables.filePaths != null ? { file_paths: variables.filePaths } : {},
);
+ const payload = response.data;
- const response = await fetch(`/api/tasks/${variables.taskId}/retry`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body,
- });
-
- const payload = (await response
- .json()
- .catch(() => ({}))) as RetryTaskResponse;
-
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
throw new Error(
payload.message || payload.error || "Failed to retry task files",
);
diff --git a/frontend/app/api/mutations/useRevokeApiKeyMutation.ts b/frontend/app/api/mutations/useRevokeApiKeyMutation.ts
index 95b1185bc..7a113afef 100644
--- a/frontend/app/api/mutations/useRevokeApiKeyMutation.ts
+++ b/frontend/app/api/mutations/useRevokeApiKeyMutation.ts
@@ -3,6 +3,7 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface RevokeApiKeyRequest {
key_id: string;
@@ -15,16 +16,16 @@ export interface RevokeApiKeyResponse {
async function revokeApiKey(
variables: RevokeApiKeyRequest,
): Promise<RevokeApiKeyResponse> {
- const response = await fetch(`/api/keys/${variables.key_id}`, {
- method: "DELETE",
- });
+ const response = await apiClient.delete<RevokeApiKeyResponse>(
+ `/keys/${variables.key_id}`,
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data as unknown as { error?: string };
throw new Error(errorData.error || "Failed to revoke API key");
}
- return response.json();
+ return response.data;
}
export const useRevokeApiKeyMutation = (
diff --git a/frontend/app/api/mutations/useS3ConfigureMutation.ts b/frontend/app/api/mutations/useS3ConfigureMutation.ts
index ad6c5eecb..43fd1d1fc 100644
--- a/frontend/app/api/mutations/useS3ConfigureMutation.ts
+++ b/frontend/app/api/mutations/useS3ConfigureMutation.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface S3ConfigurePayload {
access_key?: string;
@@ -10,14 +11,17 @@ export interface S3ConfigurePayload {
}
async function configureS3(payload: S3ConfigurePayload) {
- const res = await fetch("/api/connectors/aws_s3/configure", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(payload),
- });
- const data = await res.json();
- if (!res.ok) throw new Error(data.error || "Failed to configure S3");
- return data as { connection_id: string; status: string };
+ const res = await apiClient.post<{ connection_id: string; status: string }>(
+ "/connectors/aws_s3/configure",
+ payload,
+ );
+ if (res.status < 200 || res.status >= 300) {
+ throw new Error(
+ (res.data as unknown as { error?: string }).error ||
+ "Failed to configure S3",
+ );
+ }
+ return res.data;
}
export function useS3ConfigureMutation() {
diff --git a/frontend/app/api/mutations/useSyncConnector.ts b/frontend/app/api/mutations/useSyncConnector.ts
index 61799dce0..ea155a9b6 100644
--- a/frontend/app/api/mutations/useSyncConnector.ts
+++ b/frontend/app/api/mutations/useSyncConnector.ts
@@ -1,8 +1,8 @@
"use client";
import { useMutation, useQueryClient } from "@tanstack/react-query";
-
import type { IngestSettings } from "@/components/cloud-picker/types";
+import { apiClient } from "@/lib/api-client";
// Response types
interface SyncResponse {
@@ -46,19 +46,14 @@ export interface SyncAllPreviewResponse {
// Sync all cloud connectors
const syncAllConnectors = async (): Promise<SyncResponse> => {
- const response = await fetch("/api/connectors/sync-all", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- });
+ const response = await apiClient.post("/connectors/sync-all");
- if (!response.ok) {
- const error = await response.json();
+ if (response.status < 200 || response.status >= 300) {
+ const error = response.data ?? {};
throw new Error(error.error || "Failed to sync connectors");
}
- return response.json();
+ return response.data;
};
// Sync a specific connector type
@@ -88,20 +83,17 @@ const syncConnector = async ({
shared?: boolean;
};
}): Promise<SyncResponse> => {
- const response = await fetch(`/api/connectors/${connectorType}/sync`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(body || {}),
- });
+ const response = await apiClient.post(
+ `/connectors/${connectorType}/sync`,
+ body || {},
+ );
- if (!response.ok) {
- const error = await response.json();
+ if (response.status < 200 || response.status >= 300) {
+ const error = response.data ?? {};
throw new Error(error.error || `Failed to sync ${connectorType}`);
}
- return response.json();
+ return response.data;
};
export const useSyncAllConnectors = () => {
@@ -131,36 +123,29 @@ export const useSyncConnector = () => {
const syncConnectorPreview = async (
connectorType: string,
): Promise<SyncPreviewResponse> => {
- const response = await fetch(
- `/api/connectors/${connectorType}/sync-preview`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- },
+ const response = await apiClient.post(
+ `/connectors/${connectorType}/sync-preview`,
);
- if (!response.ok) {
- const error = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const error = response.data ?? {};
throw new Error(
error.error || `Failed to preview sync for ${connectorType}`,
);
}
- return response.json();
+ return response.data;
};
const syncAllConnectorsPreview = async (): Promise<SyncAllPreviewResponse> => {
- const response = await fetch("/api/connectors/sync-all-preview", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- });
+ const response = await apiClient.post("/connectors/sync-all-preview");
- if (!response.ok) {
- const error = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const error = response.data ?? {};
throw new Error(error.error || "Failed to preview sync");
}
- return response.json();
+ return response.data;
};
export const useSyncConnectorPreview = () => {
diff --git a/frontend/app/api/mutations/useUpdateFilter.ts b/frontend/app/api/mutations/useUpdateFilter.ts
index bb429a199..d82a58a49 100644
--- a/frontend/app/api/mutations/useUpdateFilter.ts
+++ b/frontend/app/api/mutations/useUpdateFilter.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import { KnowledgeFilter } from "../queries/useGetFiltersSearchQuery";
export interface UpdateFilterRequest {
@@ -24,23 +25,19 @@ async function updateFilter(
body.description = data.description;
if (typeof data.queryData !== "undefined") body.queryData = data.queryData;
- const response = await fetch(`/api/knowledge-filter/${data.id}`, {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(body),
- });
-
- const json = await response.json().catch(() => ({}));
+ const response = await apiClient.put<UpdateFilterResponse>(
+ `/knowledge-filter/${data.id}`,
+ body,
+ );
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
const errorMessage =
- (json && (json.error as string)) || "Failed to update knowledge filter";
+ (response.data as { error?: string }).error ||
+ "Failed to update knowledge filter";
throw new Error(errorMessage);
}
- return json as UpdateFilterResponse;
+ return response.data;
}
export const useUpdateFilter = () => {
diff --git a/frontend/app/api/mutations/useUpdateFlowsMutation.ts b/frontend/app/api/mutations/useUpdateFlowsMutation.ts
index d50cd0705..73413e800 100644
--- a/frontend/app/api/mutations/useUpdateFlowsMutation.ts
+++ b/frontend/app/api/mutations/useUpdateFlowsMutation.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
interface UpdateFlowsVariables {
flow_types: string[];
@@ -18,18 +19,17 @@ export function useUpdateFlowsMutation() {
return useMutation({
mutationFn: async (variables: UpdateFlowsVariables) => {
- const response = await fetch("/api/settings/flows/update", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(variables),
- });
+ const response = await apiClient.post(
+ "/settings/flows/update",
+ variables,
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data ?? {};
throw new Error(errorData.error || "Failed to update flows");
}
- const data = await response.json();
+ const data = response.data;
return data.results as FlowUpdateResult[];
},
onSuccess: async () => {
diff --git a/frontend/app/api/mutations/useUpdateOnboardingStateMutation.ts b/frontend/app/api/mutations/useUpdateOnboardingStateMutation.ts
index 6313e87c2..a16a18847 100644
--- a/frontend/app/api/mutations/useUpdateOnboardingStateMutation.ts
+++ b/frontend/app/api/mutations/useUpdateOnboardingStateMutation.ts
@@ -1,5 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { FunctionCall } from "@/app/chat/_types/types";
+import { apiClient } from "@/lib/api-client";
interface UpdateOnboardingStateVariables {
current_step?: number;
@@ -21,20 +22,14 @@ export const useUpdateOnboardingStateMutation = () => {
return useMutation({
mutationFn: async (variables: UpdateOnboardingStateVariables) => {
- const response = await fetch("/api/onboarding/state", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(variables),
- });
+ const response = await apiClient.post("/onboarding/state", variables);
- if (!response.ok) {
- const error = await response.json();
+ if (response.status < 200 || response.status >= 300) {
+ const error = response.data ?? {};
throw new Error(error.error || "Failed to update onboarding state");
}
- return response.json();
+ return response.data;
},
onSuccess: () => {
// Invalidate settings query to refetch updated onboarding state
diff --git a/frontend/app/api/mutations/useUpdateSettingsMutation.ts b/frontend/app/api/mutations/useUpdateSettingsMutation.ts
index edfb749a5..f2e49d5da 100644
--- a/frontend/app/api/mutations/useUpdateSettingsMutation.ts
+++ b/frontend/app/api/mutations/useUpdateSettingsMutation.ts
@@ -3,6 +3,7 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import { formatProviderErrorMessage } from "@/lib/chat-stream-errors";
import { useGetCurrentProviderModelsQuery } from "../queries/useGetModelsQuery";
import type { Settings } from "../queries/useGetSettingsQuery";
@@ -107,20 +108,20 @@ export interface UpdateSettingsResponse {
async function updateSettings(
variables: UpdateSettingsRequest,
): Promise<UpdateSettingsResponse> {
- const response = await fetch("/api/settings", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(variables),
- });
+ const response = await apiClient.post<UpdateSettingsResponse>(
+ "/settings",
+ variables,
+ );
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = (response.data ?? {}) as unknown as Record<
+ string,
+ unknown
+ >;
throw new UpdateSettingsError(response.status, errorData);
}
- return response.json();
+ return response.data;
}
export const useUpdateSettingsMutation = (
diff --git a/frontend/app/api/queries/useBrowseConnectionFiles.ts b/frontend/app/api/queries/useBrowseConnectionFiles.ts
index 4df961cf7..faefc26a9 100644
--- a/frontend/app/api/queries/useBrowseConnectionFiles.ts
+++ b/frontend/app/api/queries/useBrowseConnectionFiles.ts
@@ -3,6 +3,7 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface RemoteFile {
id: string;
@@ -62,19 +63,19 @@ export const useBrowseConnectionFiles = (
if (params.pageToken) searchParams.set("page_token", params.pageToken);
if (params.maxFiles) searchParams.set("max_files", String(params.maxFiles));
- const url = `/api/connectors/${params.connectorType}/${params.connectionId}/browse?${searchParams.toString()}`;
- const response = await fetch(url);
+ const url = `/connectors/${params.connectorType}/${params.connectionId}/browse?${searchParams.toString()}`;
+ const response = await apiClient.get<BrowseConnectionFilesResponse>(url);
- if (!response.ok) {
- const errorData = await response
- .json()
- .catch(() => ({ error: "Unknown error" }));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = (response.data ?? { error: "Unknown error" }) as {
+ error?: string;
+ };
throw new Error(
errorData.error || `Failed to browse files: ${response.status}`,
);
}
- return response.json();
+ return response.data;
}
return useQuery(
diff --git a/frontend/app/api/queries/useComponentActions.ts b/frontend/app/api/queries/useComponentActions.ts
index 4b91341db..18cad9137 100644
--- a/frontend/app/api/queries/useComponentActions.ts
+++ b/frontend/app/api/queries/useComponentActions.ts
@@ -1,4 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import { getApiError } from "@/lib/status-utils";
import type {
ComponentState,
@@ -46,12 +47,11 @@ export function useComponentSyncMutation() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (component: string): Promise<ComponentActionResponse> => {
- const res = await fetch(
- `/api/status/${encodeURIComponent(component)}/sync`,
- { method: "POST" },
+ const res = await apiClient.post<ComponentActionResponse>(
+ `/status/${encodeURIComponent(component)}/sync`,
);
- const body = await res.json().catch(() => ({}));
- if (!res.ok) {
+ const body = res.data ?? {};
+ if (res.status < 200 || res.status >= 300) {
throw new Error(getApiError(body, res.status));
}
return body as ComponentActionResponse;
@@ -87,12 +87,12 @@ export const useComponentDiagnoseQuery = (component: string | null) =>
useQuery({
queryKey: ["component-diagnose", component],
queryFn: async ({ signal }) => {
- const res = await fetch(
- `/api/status/${encodeURIComponent(component as string)}/diagnose`,
+ const res = await apiClient.get<DiagnosisResponse>(
+ `/status/${encodeURIComponent(component as string)}/diagnose`,
{ signal },
);
- const body = await res.json().catch(() => ({}));
- if (!res.ok) {
+ const body = res.data ?? {};
+ if (res.status < 200 || res.status >= 300) {
throw new Error(getApiError(body, res.status));
}
return body as DiagnosisResponse;
diff --git a/frontend/app/api/queries/useComponentLogsQuery.ts b/frontend/app/api/queries/useComponentLogsQuery.ts
index c31ea6f50..98eca5ba2 100644
--- a/frontend/app/api/queries/useComponentLogsQuery.ts
+++ b/frontend/app/api/queries/useComponentLogsQuery.ts
@@ -1,4 +1,5 @@
import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import { getApiError } from "@/lib/status-utils";
export interface LogEntry {
@@ -19,15 +20,15 @@ async function fetchComponentLogs(
tail = 100,
signal?: AbortSignal,
): Promise<ComponentLogsResponse> {
- const response = await fetch(
- `/api/status/${encodeURIComponent(component)}/logs?tail=${tail}`,
+ const response = await apiClient.get<ComponentLogsResponse>(
+ `/status/${encodeURIComponent(component)}/logs?tail=${tail}`,
{ signal },
);
- if (!response.ok) {
- const body = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const body = response.data ?? {};
throw new Error(getApiError(body, response.status));
}
- return response.json() as Promise<ComponentLogsResponse>;
+ return response.data;
}
export const useComponentLogsQuery = (
diff --git a/frontend/app/api/queries/useConnectorOAuthConfigQuery.ts b/frontend/app/api/queries/useConnectorOAuthConfigQuery.ts
index 6fc68038d..12e2e668a 100644
--- a/frontend/app/api/queries/useConnectorOAuthConfigQuery.ts
+++ b/frontend/app/api/queries/useConnectorOAuthConfigQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface ConnectorOAuthConfigStatus {
client_id_set: boolean;
@@ -13,9 +14,13 @@ export type ConnectorOAuthConfigMap = Record<
>;
async function fetchConnectorOAuthConfig(): Promise<ConnectorOAuthConfigMap> {
- const res = await fetch("/api/connectors/oauth-config");
- if (!res.ok) throw new Error("Failed to fetch connector OAuth config");
- const data = await res.json();
+ const res = await apiClient.get<{ credentials: ConnectorOAuthConfigMap }>(
+ "/connectors/oauth-config",
+ );
+ if (res.status < 200 || res.status >= 300) {
+ throw new Error("Failed to fetch connector OAuth config");
+ }
+ const data = res.data;
return data.credentials as ConnectorOAuthConfigMap;
}
diff --git a/frontend/app/api/queries/useConsoleStatusQuery.ts b/frontend/app/api/queries/useConsoleStatusQuery.ts
index e4bb70ec9..570f43ad4 100644
--- a/frontend/app/api/queries/useConsoleStatusQuery.ts
+++ b/frontend/app/api/queries/useConsoleStatusQuery.ts
@@ -1,4 +1,5 @@
import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import { getApiError } from "@/lib/status-utils";
export type ComponentState = "healthy" | "degraded" | "unhealthy" | "unknown";
@@ -33,12 +34,12 @@ export interface ConsoleStatusResponse {
}
async function fetchConsoleStatus(): Promise<ConsoleStatusResponse> {
- const response = await fetch("/api/status");
- if (!response.ok) {
- const body = await response.json().catch(() => ({}));
+ const response = await apiClient.get<ConsoleStatusResponse>("/status");
+ if (response.status < 200 || response.status >= 300) {
+ const body = response.data;
throw new Error(getApiError(body, response.status));
}
- return response.json() as Promise<ConsoleStatusResponse>;
+ return response.data;
}
export const useConsoleStatusQuery = (
diff --git a/frontend/app/api/queries/useDeleteSessionMutation.ts b/frontend/app/api/queries/useDeleteSessionMutation.ts
index 996e8a44d..a7f49f8a9 100644
--- a/frontend/app/api/queries/useDeleteSessionMutation.ts
+++ b/frontend/app/api/queries/useDeleteSessionMutation.ts
@@ -4,6 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import type { EndpointType } from "@/contexts/chat-context";
+import { apiClient } from "@/lib/api-client";
interface DeleteSessionParams {
sessionId: string;
@@ -25,18 +26,16 @@ export const useDeleteSessionMutation = (
return useMutation<DeleteSessionResponse, Error, DeleteSessionParams>({
mutationFn: async ({ sessionId }: DeleteSessionParams) => {
- const response = await fetch(`/api/sessions/${sessionId}`, {
- method: "DELETE",
- });
+ const response = await apiClient.delete(`/sessions/${sessionId}`);
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data ?? {};
throw new Error(
errorData.error || `Failed to delete session: ${response.status}`,
);
}
- return response.json();
+ return response.data;
},
onSettled: (_data, _error, variables) => {
// Invalidate conversations query to refresh the list
diff --git a/frontend/app/api/queries/useDoclingHealthQuery.ts b/frontend/app/api/queries/useDoclingHealthQuery.ts
index e9acb4ddb..763665b8e 100644
--- a/frontend/app/api/queries/useDoclingHealthQuery.ts
+++ b/frontend/app/api/queries/useDoclingHealthQuery.ts
@@ -3,6 +3,7 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface DoclingHealthResponse {
// "degraded": docling-serve is up but slow to answer (busy converting), so
@@ -13,15 +14,11 @@ export interface DoclingHealthResponse {
async function checkDoclingHealth(): Promise<DoclingHealthResponse> {
try {
- const response = await fetch("/api/docling/health", {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- });
+ const response =
+ await apiClient.get<DoclingHealthResponse>("/docling/health");
- if (response.ok) {
- const body = await response.json().catch(() => ({}));
+ if (response.status >= 200 && response.status < 300) {
+ const body = response.data;
if (body?.status === "degraded") {
return { status: "degraded", message: body.message };
}
diff --git a/frontend/app/api/queries/useGetAllFiltersQuery.ts b/frontend/app/api/queries/useGetAllFiltersQuery.ts
index 2bcf54933..04e110bab 100644
--- a/frontend/app/api/queries/useGetAllFiltersQuery.ts
+++ b/frontend/app/api/queries/useGetAllFiltersQuery.ts
@@ -3,17 +3,16 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import type { KnowledgeFilter } from "./useGetFiltersSearchQuery";
async function getAllFilters(): Promise<KnowledgeFilter[]> {
- const response = await fetch("/api/knowledge-filter/search", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ query: "", limit: 1000 }),
- });
-
- const json = await response.json();
- if (!response.ok || !json.success) {
+ const response = await apiClient.post<{
+ success?: boolean;
+ filters?: KnowledgeFilter[];
+ }>("/knowledge-filter/search", { query: "", limit: 1000 });
+ const json = response.data;
+ if (response.status < 200 || response.status >= 300 || !json.success) {
return [];
}
return (json.filters || []) as KnowledgeFilter[];
diff --git a/frontend/app/api/queries/useGetApiKeysQuery.ts b/frontend/app/api/queries/useGetApiKeysQuery.ts
index f0f585c02..b9a881d9a 100644
--- a/frontend/app/api/queries/useGetApiKeysQuery.ts
+++ b/frontend/app/api/queries/useGetApiKeysQuery.ts
@@ -1,4 +1,5 @@
import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface ApiKey {
key_id: string;
@@ -13,9 +14,9 @@ export interface GetApiKeysResponse {
}
async function getApiKeys(): Promise<GetApiKeysResponse> {
- const response = await fetch("/api/keys");
- if (response.ok) {
- return await response.json();
+ const response = await apiClient.get<GetApiKeysResponse>("/keys");
+ if (response.status >= 200 && response.status < 300) {
+ return response.data;
}
throw new Error("Failed to fetch API keys");
}
diff --git a/frontend/app/api/queries/useGetConnectorTokenQuery.ts b/frontend/app/api/queries/useGetConnectorTokenQuery.ts
index 5a8fd4839..c70e98820 100644
--- a/frontend/app/api/queries/useGetConnectorTokenQuery.ts
+++ b/frontend/app/api/queries/useGetConnectorTokenQuery.ts
@@ -1,4 +1,5 @@
import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
interface TokenResponse {
access_token: string;
@@ -26,18 +27,18 @@ export const useGetConnectorTokenQuery = (
throw new Error("Connection ID is required for fetching token");
}
- let url = `/api/connectors/${connectorType}/token?connection_id=${connectionId}`;
+ let url = `/connectors/${connectorType}/token?connection_id=${connectionId}`;
if (resource) {
url += `&resource=${encodeURIComponent(resource)}`;
}
- const response = await fetch(url);
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
+ const response = await apiClient.get<TokenResponse>(url);
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data ?? {};
throw new Error(errorData.error || "Failed to fetch access token");
}
- return response.json();
+ return response.data;
},
enabled: !!connectorType && !!connectionId && (options?.enabled ?? true),
staleTime: 1000 * 60 * 5, // 5 minutes
diff --git a/frontend/app/api/queries/useGetConnectorsQuery.ts b/frontend/app/api/queries/useGetConnectorsQuery.ts
index 152d37b40..35f275ca2 100644
--- a/frontend/app/api/queries/useGetConnectorsQuery.ts
+++ b/frontend/app/api/queries/useGetConnectorsQuery.ts
@@ -8,6 +8,7 @@ import {
import { toast } from "sonner";
import { useAuth } from "@/contexts/auth-context";
import { useBrand, useIsCloudBrand } from "@/contexts/brand-context";
+import { apiClient } from "@/lib/api-client";
import {
isConnectorShownInWorkspace,
isConnectorTypeVisible,
@@ -161,9 +162,9 @@ export interface GetConnectorsResponse {
async function fetchWorkspaceConnectorAccess(): Promise<
Record<string, boolean>
> {
- const response = await fetch("/api/connectors/workspace-policy");
- if (!response.ok) return {};
- const data = await response.json();
+ const response = await apiClient.get("/connectors/workspace-policy");
+ if (response.status < 200 || response.status >= 300) return {};
+ const data = response.data;
return data?.access && typeof data.access === "object" ? data.access : {};
}
@@ -174,18 +175,31 @@ export const useGetConnectorsQuery = (
useConnectorsQueryKey();
async function getConnectors(): Promise<Connector[]> {
- const connectorsResponse = await fetch("/api/connectors");
- if (!connectorsResponse.ok) {
+ const connectorsResponse = await apiClient.get<{
+ connectors: Record<
+ string,
+ {
+ kind?: string;
+ name: string;
+ description: string;
+ icon: string;
+ available?: boolean;
+ }
+ >;
+ }>("/connectors");
+ if (connectorsResponse.status < 200 || connectorsResponse.status >= 300) {
throw new Error("Failed to fetch available connectors");
}
- const { connectors: connectorsMap } = await connectorsResponse.json();
+ const { connectors: connectorsMap } = connectorsResponse.data;
const connectorTypes = Object.keys(connectorsMap);
const connectorsWithStatus = await Promise.all(
connectorTypes.map(async (type) => {
const connectorData = connectorsMap[type];
- const statusResponse = await fetch(`/api/connectors/${type}/status`);
+ const statusResponse = await apiClient.get(
+ `/connectors/${type}/status`,
+ );
let status: Connector["status"] = "not_connected";
let connectionId: string | undefined;
@@ -195,8 +209,8 @@ export const useGetConnectorsQuery = (
// "bucket" connectors use credential-based auth (Azure Blob, S3, IBM COS)
const requiresOAuth = connectorData.kind === "oauth";
- if (statusResponse.ok) {
- const statusData = await statusResponse.json();
+ if (statusResponse.status >= 200 && statusResponse.status < 300) {
+ const statusData = statusResponse.data;
const connections = statusData.connections || [];
const activeConnection = connections.find(
(conn: Connection) => conn.is_active && conn.is_authenticated,
@@ -299,13 +313,13 @@ export const useGetConnectorAccessQuery = (
const { isIbmAuthMode } = useAuth();
async function fetchConnectorAccess(): Promise<ConnectorAccessItem[]> {
- const response = await fetch("/api/connectors/user-access");
- if (!response.ok) {
+ const response = await apiClient.get("/connectors/user-access");
+ if (response.status < 200 || response.status >= 300) {
throw new Error(
`Failed to fetch connectors permission (${response.status})`,
);
}
- const data = await response.json();
+ const data = response.data;
const connectors = Array.isArray(data.connectors) ? data.connectors : [];
const deploymentCtx = { isCloudBrand, isIbmAuthMode };
return filterConnectorAccessItems(connectors, deploymentCtx);
@@ -333,18 +347,16 @@ export const useUpdateConnectorAccessMutation = () => {
mutationFn: async (
access: Record<string, boolean>,
): Promise<ConnectorAccessItem[]> => {
- const response = await fetch("/api/connectors/user-access", {
- method: "PUT",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ access }),
+ const response = await apiClient.put("/connectors/user-access", {
+ access,
});
- if (!response.ok) {
- const result = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const result = response.data ?? {};
throw new Error(
result.error || "Failed to update connectors permission",
);
}
- const data = await response.json();
+ const data = response.data;
const connectors = Array.isArray(data.connectors) ? data.connectors : [];
return filterConnectorAccessItems(connectors, deploymentCtx);
},
diff --git a/frontend/app/api/queries/useGetConversationsQuery.ts b/frontend/app/api/queries/useGetConversationsQuery.ts
index a3ae9b5cc..e263f721f 100644
--- a/frontend/app/api/queries/useGetConversationsQuery.ts
+++ b/frontend/app/api/queries/useGetConversationsQuery.ts
@@ -5,6 +5,7 @@ import {
} from "@tanstack/react-query";
import type { EndpointType } from "@/contexts/chat-context";
import { useChat } from "@/contexts/chat-context";
+import { apiClient } from "@/lib/api-client";
export interface RawConversation {
response_id: string;
@@ -62,18 +63,19 @@ export const useGetConversationsQuery = (
try {
// Fetch from the selected endpoint only
const apiEndpoint =
- endpoint === "chat" ? "/api/chat/history" : "/api/langflow/history";
+ endpoint === "chat" ? "/chat/history" : "/langflow/history";
- const response = await fetch(apiEndpoint, {
- signal: context.signal,
- });
+ const response = await apiClient.get<ConversationHistoryResponse>(
+ apiEndpoint,
+ { signal: context.signal },
+ );
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
console.error(`Failed to fetch conversations: ${response.status}`);
return [];
}
- const history: ConversationHistoryResponse = await response.json();
+ const history = response.data;
const rawConversations = history.conversations || [];
// Cast conversations to proper type and ensure endpoint is correct
diff --git a/frontend/app/api/queries/useGetFilterByIdQuery.ts b/frontend/app/api/queries/useGetFilterByIdQuery.ts
index 090b6f87a..00b41589f 100644
--- a/frontend/app/api/queries/useGetFilterByIdQuery.ts
+++ b/frontend/app/api/queries/useGetFilterByIdQuery.ts
@@ -1,16 +1,16 @@
+import { apiClient } from "@/lib/api-client";
import type { KnowledgeFilter } from "./useGetFiltersSearchQuery";
export async function getFilterById(
filterId: string,
): Promise<KnowledgeFilter | null> {
try {
- const response = await fetch(`/api/knowledge-filter/${filterId}`, {
- method: "GET",
- headers: { "Content-Type": "application/json" },
- });
-
- const json = await response.json();
- if (!response.ok || !json.success) {
+ const response = await apiClient.get<{
+ success?: boolean;
+ filter?: KnowledgeFilter;
+ }>(`/knowledge-filter/${filterId}`);
+ const json = response.data;
+ if (response.status < 200 || response.status >= 300 || !json.success) {
return null;
}
return json.filter as KnowledgeFilter;
diff --git a/frontend/app/api/queries/useGetFiltersSearchQuery.ts b/frontend/app/api/queries/useGetFiltersSearchQuery.ts
index f85f948fc..109612baf 100644
--- a/frontend/app/api/queries/useGetFiltersSearchQuery.ts
+++ b/frontend/app/api/queries/useGetFiltersSearchQuery.ts
@@ -3,6 +3,7 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface KnowledgeFilter {
id: string;
@@ -23,14 +24,12 @@ export const useGetFiltersSearchQuery = (
const queryClient = useQueryClient();
async function getFilters(): Promise<KnowledgeFilter[]> {
- const response = await fetch("/api/knowledge-filter/search", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ query: search, limit }),
- });
-
- const json = await response.json();
- if (!response.ok || !json.success) {
+ const response = await apiClient.post<{
+ success?: boolean;
+ filters?: KnowledgeFilter[];
+ }>("/knowledge-filter/search", { query: search, limit });
+ const json = response.data;
+ if (response.status < 200 || response.status >= 300 || !json.success) {
// ensure we always return a KnowledgeFilter[] to satisfy the return type
return [];
}
diff --git a/frontend/app/api/queries/useGetFlowsUpdatesQuery.ts b/frontend/app/api/queries/useGetFlowsUpdatesQuery.ts
index d300f2364..3f3dcfc57 100644
--- a/frontend/app/api/queries/useGetFlowsUpdatesQuery.ts
+++ b/frontend/app/api/queries/useGetFlowsUpdatesQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export type FlowUpdate = {
flow_type: "nudges" | "retrieval" | "ingest" | "url_ingest";
@@ -11,11 +12,13 @@ export function useGetFlowsUpdatesQuery(options?: { enabled?: boolean }) {
return useQuery({
queryKey: ["flows", "updates-available"],
queryFn: async () => {
- const response = await fetch("/api/settings/flows/updates-available");
- if (!response.ok) {
+ const response = await apiClient.get<{ updates: FlowUpdate[] }>(
+ "/settings/flows/updates-available",
+ );
+ if (response.status < 200 || response.status >= 300) {
throw new Error("Failed to fetch flow updates");
}
- const data = await response.json();
+ const data = response.data;
return data.updates as FlowUpdate[];
},
...options,
diff --git a/frontend/app/api/queries/useGetModelProvidersQuery.ts b/frontend/app/api/queries/useGetModelProvidersQuery.ts
index c6a0c1ccf..b0b985eda 100644
--- a/frontend/app/api/queries/useGetModelProvidersQuery.ts
+++ b/frontend/app/api/queries/useGetModelProvidersQuery.ts
@@ -3,6 +3,7 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface ModelProviderEntry {
name: string;
@@ -38,11 +39,12 @@ export const useGetModelProvidersQuery = (
// two-field shape fetches the enriched response immediately.
queryKey: ["models", "providers", "v2"] as const,
queryFn: async (): Promise<ModelProvidersResponse> => {
- const response = await fetch("/api/models/providers");
- if (!response.ok) {
+ const response =
+ await apiClient.get<ModelProvidersResponse>("/models/providers");
+ if (response.status < 200 || response.status >= 300) {
throw new Error("Failed to fetch the model providers");
}
- return (await response.json()) as ModelProvidersResponse;
+ return response.data;
},
// Run mode and the config file are fixed for the life of the backend
// process, so this never goes stale within a session. Editing
diff --git a/frontend/app/api/queries/useGetModelsQuery.ts b/frontend/app/api/queries/useGetModelsQuery.ts
index a7b72ca90..b7a7b45f0 100644
--- a/frontend/app/api/queries/useGetModelsQuery.ts
+++ b/frontend/app/api/queries/useGetModelsQuery.ts
@@ -4,6 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import type { CatalogModel } from "@/components/models/catalog-models";
+import { apiClient } from "@/lib/api-client";
import { formatProviderErrorMessage } from "@/lib/chat-stream-errors";
import { useGetSettingsQuery } from "./useGetSettingsQuery";
@@ -44,12 +45,15 @@ export interface IBMModelsParams {
}
async function throwModelsFetchError(
- response: Response,
+ response: { data?: unknown },
fallback: string,
): Promise<never> {
- const data = await response.json().catch(() => ({}));
+ const data = response.data ?? {};
const raw =
- data && typeof data === "object" && typeof data.error === "string"
+ data &&
+ typeof data === "object" &&
+ "error" in data &&
+ typeof data.error === "string"
? data.error
: fallback;
throw new Error(formatProviderErrorMessage(raw));
@@ -72,13 +76,12 @@ export const useGetOpenAIModelsQuery = (
body.api_key = apiKey;
}
- const response = await fetch("/api/models/openai", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
- if (response.ok) {
- return (await response.json()) as ModelsResponse;
+ const response = await apiClient.post<ModelsResponse>(
+ "/models/openai",
+ body,
+ );
+ if (response.status >= 200 && response.status < 300) {
+ return response.data;
}
return throwModelsFetchError(response, "Failed to fetch OpenAI models");
},
@@ -108,13 +111,12 @@ export const useGetAnthropicModelsQuery = (
body.api_key = apiKey;
}
- const response = await fetch("/api/models/anthropic", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
- if (response.ok) {
- return (await response.json()) as ModelsResponse;
+ const response = await apiClient.post<ModelsResponse>(
+ "/models/anthropic",
+ body,
+ );
+ if (response.status >= 200 && response.status < 300) {
+ return response.data;
}
return throwModelsFetchError(
response,
@@ -141,14 +143,12 @@ export const useGetOllamaModelsQuery = (
{
queryKey: ["models", "ollama", endpoint] as const,
queryFn: async (): Promise<ModelsResponse> => {
- const url = new URL("/api/models/ollama", window.location.origin);
- if (endpoint) {
- url.searchParams.set("endpoint", endpoint);
- }
-
- const response = await fetch(url.toString());
- if (response.ok) {
- return (await response.json()) as ModelsResponse;
+ const path = endpoint
+ ? `/models/ollama?endpoint=${encodeURIComponent(endpoint)}`
+ : "/models/ollama";
+ const response = await apiClient.get<ModelsResponse>(path);
+ if (response.status >= 200 && response.status < 300) {
+ return response.data;
}
return throwModelsFetchError(response, "Failed to fetch Ollama models");
},
@@ -197,13 +197,12 @@ export const useGetIBMModelsQuery = (
body.api_key = apiKey;
}
- const response = await fetch("/api/models/ibm", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
- if (response.ok) {
- return (await response.json()) as ModelsResponse;
+ const response = await apiClient.post<ModelsResponse>(
+ "/models/ibm",
+ body,
+ );
+ if (response.status >= 200 && response.status < 300) {
+ return response.data;
}
return throwModelsFetchError(response, "Failed to fetch IBM models");
},
@@ -320,9 +319,10 @@ export const useGetModelCatalogQuery = (
{
queryKey: ["models", "catalog"] as const,
queryFn: async (): Promise<ModelCatalogResponse> => {
- const response = await fetch("/api/models/catalog");
- if (response.ok) {
- return (await response.json()) as ModelCatalogResponse;
+ const response =
+ await apiClient.get<ModelCatalogResponse>("/models/catalog");
+ if (response.status >= 200 && response.status < 300) {
+ return response.data;
}
return throwModelsFetchError(
response,
diff --git a/frontend/app/api/queries/useGetNudgesQuery.ts b/frontend/app/api/queries/useGetNudgesQuery.ts
index 67b375bfb..8ee96a3a6 100644
--- a/frontend/app/api/queries/useGetNudgesQuery.ts
+++ b/frontend/app/api/queries/useGetNudgesQuery.ts
@@ -4,6 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import { useChat } from "@/contexts/chat-context";
+import { apiClient } from "@/lib/api-client";
import { useProviderHealthQuery } from "./useProviderHealthQuery";
type Nudge = string;
@@ -68,15 +69,12 @@ export const useGetNudgesQuery = (
requestBody.score_threshold = scoreThreshold;
}
- const response = await fetch(`/api/nudges${chatId ? `/${chatId}` : ""}`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(requestBody),
- signal: context.signal,
- });
- const data = await response.json();
+ const response = await apiClient.post(
+ `/nudges${chatId ? `/${chatId}` : ""}`,
+ requestBody,
+ { signal: context.signal },
+ );
+ const data = response.data;
if (data.response && typeof data.response === "string") {
return data.response.split("\n").filter(Boolean);
diff --git a/frontend/app/api/queries/useGetSearchAggregations.ts b/frontend/app/api/queries/useGetSearchAggregations.ts
index b18ae85b2..a486a497f 100644
--- a/frontend/app/api/queries/useGetSearchAggregations.ts
+++ b/frontend/app/api/queries/useGetSearchAggregations.ts
@@ -3,6 +3,7 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface FacetBucket {
key: string;
@@ -32,15 +33,13 @@ export const useGetSearchAggregations = (
const queryClient = useQueryClient();
async function fetchAggregations(): Promise<SearchAggregations> {
- const response = await fetch("/api/search", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ query, limit, scoreThreshold }),
- });
+ const response = await apiClient.post<{
+ aggregations?: SearchAggregations;
+ error?: string;
+ }>("/search", { query, limit, scoreThreshold });
+ const json = response.data;
- const json = await response.json().catch(() => ({}));
-
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
throw new Error(
(json && json.error) || "Failed to load search aggregations",
);
diff --git a/frontend/app/api/queries/useGetSearchQuery.ts b/frontend/app/api/queries/useGetSearchQuery.ts
index e97b9f7bf..a0cddbacd 100644
--- a/frontend/app/api/queries/useGetSearchQuery.ts
+++ b/frontend/app/api/queries/useGetSearchQuery.ts
@@ -4,6 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import type { ParsedQueryData } from "@/contexts/knowledge-filter-context";
+import { apiClient } from "@/lib/api-client";
import { SEARCH_CONSTANTS } from "@/lib/constants";
import { buildSearchPayloadFilters } from "@/lib/filter-normalization";
@@ -161,24 +162,19 @@ export const useGetSearchQuery = (
buildSearchPayloadFilters(queryData.filters) ?? undefined;
}
- const response = await fetch(`/api/search`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(searchPayload),
- });
+ const response = await apiClient.post(`/search`, searchPayload);
- if (!response.ok) {
- const errorData = await response
- .json()
- .catch(() => ({ error: "Unknown error" }));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData =
+ response.data && typeof response.data === "object"
+ ? (response.data as { error?: string })
+ : { error: "Unknown error" };
throw new Error(
errorData.error || `Search failed with status ${response.status}`,
);
}
- const data = await response.json();
+ const data = response.data;
// Group chunks by filename to create file results similar to page.tsx
const fileMap = new Map<
string,
diff --git a/frontend/app/api/queries/useGetSettingsQuery.ts b/frontend/app/api/queries/useGetSettingsQuery.ts
index 462b9f6e2..7c73bddde 100644
--- a/frontend/app/api/queries/useGetSettingsQuery.ts
+++ b/frontend/app/api/queries/useGetSettingsQuery.ts
@@ -4,6 +4,7 @@ import {
useQueryClient,
} from "@tanstack/react-query";
import type { FunctionCall } from "@/app/chat/_types/types";
+import { apiClient } from "@/lib/api-client";
export interface AgentSettings {
llm_model?: string;
@@ -112,9 +113,9 @@ export interface Settings {
}
export async function getSettings(): Promise<Settings> {
- const response = await fetch("/api/settings");
- if (response.ok) {
- return await response.json();
+ const response = await apiClient.get<Settings>("/settings");
+ if (response.status >= 200 && response.status < 300) {
+ return response.data;
} else {
throw new Error("Failed to fetch settings");
}
diff --git a/frontend/app/api/queries/useGetTaskQuery.ts b/frontend/app/api/queries/useGetTaskQuery.ts
index cf36e598a..1452b5ec3 100644
--- a/frontend/app/api/queries/useGetTaskQuery.ts
+++ b/frontend/app/api/queries/useGetTaskQuery.ts
@@ -1,5 +1,6 @@
import { type UseQueryOptions, useQuery } from "@tanstack/react-query";
import type { Task } from "@/app/api/queries/useGetTasksQuery";
+import { apiClient } from "@/lib/api-client";
const TASK_DETAIL_QUERY_KEY = ["tasks", "detail"] as const;
@@ -19,16 +20,16 @@ export function useGetTaskQuery(
if (!taskId) {
return null;
}
- const response = await fetch(
- `/api/tasks/${encodeURIComponent(taskId)}/enhanced`,
+ const response = await apiClient.get<Task>(
+ `/tasks/${encodeURIComponent(taskId)}/enhanced`,
);
if (response.status === 404) {
return null;
}
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
throw new Error("Failed to fetch task");
}
- return response.json() as Promise<Task>;
+ return response.data;
},
...options,
enabled: options?.enabled ?? !!taskId,
diff --git a/frontend/app/api/queries/useGetTasksQuery.ts b/frontend/app/api/queries/useGetTasksQuery.ts
index 442d66128..0e12c39a4 100644
--- a/frontend/app/api/queries/useGetTasksQuery.ts
+++ b/frontend/app/api/queries/useGetTasksQuery.ts
@@ -3,6 +3,7 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
/** Component that failed, from GET /tasks/enhanced file metadata. */
export type TaskFailureComponent =
@@ -89,13 +90,13 @@ export interface TasksResponse {
export const TASKS_QUERY_KEY = ["tasks", "enhanced"] as const;
async function getTasks(): Promise<Task[]> {
- const response = await fetch("/api/tasks/enhanced");
+ const response = await apiClient.get<TasksResponse>("/tasks/enhanced");
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
throw new Error("Failed to fetch tasks");
}
- const data: TasksResponse = await response.json();
+ const data = response.data;
return data.tasks || [];
}
diff --git a/frontend/app/api/queries/useIngestPreviewQuery.ts b/frontend/app/api/queries/useIngestPreviewQuery.ts
index 2b8ce9b89..455d326e2 100644
--- a/frontend/app/api/queries/useIngestPreviewQuery.ts
+++ b/frontend/app/api/queries/useIngestPreviewQuery.ts
@@ -1,4 +1,5 @@
import { type QueryKey, useQuery, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface DoclingPreviewStats {
page_count: number;
@@ -72,14 +73,14 @@ async function fetchPreviewJson<T>(
filePath?: string | null,
options?: { notFoundAsNull?: boolean },
): Promise<T | null> {
- const response = await fetch(withFileParam(path, filePath));
+ const response = await apiClient.get<T>(withFileParam(path, filePath));
if (options?.notFoundAsNull && response.status === 404) {
return null;
}
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
throw new Error(`Preview unavailable (${response.status})`);
}
- return response.json() as Promise<T>;
+ return response.data;
}
/**
@@ -99,7 +100,7 @@ export function useDoclingPreviewQuery(
queryKey: ingestPreviewQueryKeys.docling(taskId, filePath),
queryFn: () =>
fetchPreviewJson<DoclingPreviewResponse>(
- `/api/ingest/preview/${taskId}/docling`,
+ `/ingest/preview/${taskId}/docling`,
filePath,
{ notFoundAsNull: true },
),
@@ -133,7 +134,7 @@ export function useIndexProofQuery(
queryKey: ingestPreviewQueryKeys.indexProof(taskId, filePath) as QueryKey,
queryFn: () =>
fetchPreviewJson<IndexProofResponse>(
- `/api/ingest/preview/${taskId}/index-proof`,
+ `/ingest/preview/${taskId}/index-proof`,
filePath,
),
enabled: enabled && !!taskId,
diff --git a/frontend/app/api/queries/useListFiles.ts b/frontend/app/api/queries/useListFiles.ts
index 396975022..a14306a10 100644
--- a/frontend/app/api/queries/useListFiles.ts
+++ b/frontend/app/api/queries/useListFiles.ts
@@ -3,6 +3,7 @@ import {
useQuery,
useQueryClient,
} from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
import type { File } from "./useGetSearchQuery";
export interface ListFilesParams {
@@ -50,20 +51,18 @@ export const useListFiles = (
if (params.afterKey)
searchParams.set("after_key", JSON.stringify(params.afterKey));
- const url = `/api/files?${searchParams.toString()}`; //internal (cookie auth)
+ const url = `/files?${searchParams.toString()}`; //internal (cookie auth)
- const response = await fetch(url);
+ const response = await apiClient.get(url);
- if (!response.ok) {
- const errorData = await response
- .json()
- .catch(() => ({ error: "Unknown error" }));
+ if (response.status < 200 || response.status >= 300) {
+ const errorData = response.data ?? { error: "Unknown error" };
throw new Error(
errorData.error || `Failed to list files: ${response.status}`,
);
}
- const data = await response.json();
+ const data = response.data;
const files: File[] = (data.files || []).map(
(f: Record<string, unknown>) => ({
diff --git a/frontend/app/api/queries/useProviderHealthQuery.ts b/frontend/app/api/queries/useProviderHealthQuery.ts
index f62992be9..897adc9fa 100644
--- a/frontend/app/api/queries/useProviderHealthQuery.ts
+++ b/frontend/app/api/queries/useProviderHealthQuery.ts
@@ -5,6 +5,7 @@ import {
} from "@tanstack/react-query";
import { useChat } from "@/contexts/chat-context";
import { usePermissions } from "@/hooks/use-permissions";
+import { apiClient } from "@/lib/api-client";
import { useGetSettingsQuery } from "./useGetSettingsQuery";
import { useGetTasksQuery } from "./useGetTasksQuery";
@@ -93,16 +94,18 @@ export const useProviderHealthQuery = (
url.searchParams.set("test_completion", "true");
}
- const response = await fetch(url.toString());
+ const response = await apiClient.get<ProviderHealthResponse>(
+ `/provider/health${url.search}`,
+ );
- if (response.ok) {
- const data = (await response.json()) as ProviderHealthResponse;
+ if (response.status >= 200 && response.status < 300) {
+ const data = response.data;
if (hasChatError) {
setChatError(false);
}
return data;
} else if (response.status === 503) {
- const errorData = await response.json().catch(() => ({}));
+ const errorData = response.data ?? {};
return {
status: "unhealthy",
message: errorData.message || "Provider validation failed",
@@ -115,7 +118,7 @@ export const useProviderHealthQuery = (
warnings: errorData.warnings,
};
} else {
- const errorData = await response.json().catch(() => ({}));
+ const errorData = response.data ?? {};
return {
status: "error",
message: errorData.message || "Failed to check provider health",
diff --git a/frontend/app/api/queries/useS3BucketStatusQuery.ts b/frontend/app/api/queries/useS3BucketStatusQuery.ts
index eb47248b6..b727ac02a 100644
--- a/frontend/app/api/queries/useS3BucketStatusQuery.ts
+++ b/frontend/app/api/queries/useS3BucketStatusQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface S3BucketStatus {
name: string;
@@ -9,15 +10,14 @@ export interface S3BucketStatus {
async function fetchS3BucketStatus(
connectionId: string,
): Promise<S3BucketStatus[]> {
- const res = await fetch(
- `/api/connectors/aws_s3/${connectionId}/bucket-status`,
+ const res = await apiClient.get<{ buckets: S3BucketStatus[] }>(
+ `/connectors/aws_s3/${connectionId}/bucket-status`,
);
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
+ if (res.status < 200 || res.status >= 300) {
+ const err = (res.data ?? {}) as { error?: string };
throw new Error(err.error || "Failed to fetch bucket status");
}
- const data = await res.json();
- return data.buckets as S3BucketStatus[];
+ return res.data.buckets;
}
export function useS3BucketStatusQuery(
diff --git a/frontend/app/api/queries/useS3DefaultsQuery.ts b/frontend/app/api/queries/useS3DefaultsQuery.ts
index beb64d8f3..59f3133fa 100644
--- a/frontend/app/api/queries/useS3DefaultsQuery.ts
+++ b/frontend/app/api/queries/useS3DefaultsQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface S3Defaults {
access_key_set: boolean;
@@ -10,9 +11,11 @@ export interface S3Defaults {
}
async function fetchS3Defaults(): Promise<S3Defaults> {
- const res = await fetch("/api/connectors/aws_s3/defaults");
- if (!res.ok) throw new Error("Failed to fetch S3 defaults");
- return res.json();
+ const res = await apiClient.get<S3Defaults>("/connectors/aws_s3/defaults");
+ if (res.status < 200 || res.status >= 300) {
+ throw new Error("Failed to fetch S3 defaults");
+ }
+ return res.data;
}
export function useS3DefaultsQuery(options?: { enabled?: boolean }) {
diff --git a/frontend/app/auth/callback/page.tsx b/frontend/app/auth/callback/page.tsx
index 2a2e91977..15209186d 100644
--- a/frontend/app/auth/callback/page.tsx
+++ b/frontend/app/auth/callback/page.tsx
@@ -20,6 +20,7 @@ import {
CardTitle,
} from "@/components/ui/card";
import { useAuth } from "@/contexts/auth-context";
+import { apiClient } from "@/lib/api-client";
import { decodeBase64 } from "@/lib/utils";
// remove from localStorage any keys related to the OAuth flow
@@ -81,17 +82,13 @@ function AuthCallbackContent() {
code: string;
state: string;
}) => {
- const response = await fetch("/api/auth/callback", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- connection_id: params.connectionId,
- authorization_code: params.code,
- state: params.state,
- }),
+ const response = await apiClient.post("/auth/callback", {
+ connection_id: params.connectionId,
+ authorization_code: params.code,
+ state: params.state,
});
- const result = await response.json();
- if (!response.ok) {
+ const result = response.data;
+ if (response.status < 200 || response.status >= 300) {
throw new Error(result.error || "Authentication failed");
}
return result as { purpose?: string };
diff --git a/frontend/app/chat/page.tsx b/frontend/app/chat/page.tsx
index edc7de182..58054aec0 100644
--- a/frontend/app/chat/page.tsx
+++ b/frontend/app/chat/page.tsx
@@ -15,6 +15,7 @@ import { useOnboardingState } from "@/hooks/use-onboarding-state";
import { useSupportedFileTypes } from "@/hooks/use-supported-file-types";
import { useChatStreaming } from "@/hooks/useChatStreaming";
import { trackLLMCall } from "@/lib/analytics";
+import { apiClient } from "@/lib/api-client";
import {
dedupeConsecutiveErrorMessages,
formatProviderErrorMessage,
@@ -781,17 +782,14 @@ function ChatPage() {
requestBody.filter_id = conversationFilter.id;
}
- const response = await fetch(apiEndpoint, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(requestBody),
- });
+ const response = await apiClient.post(
+ apiEndpoint.replace(/^\/api/, ""),
+ requestBody,
+ );
- const result = await response.json();
+ const result = response.data;
- if (response.ok) {
+ if (response.status >= 200 && response.status < 300) {
const assistantMessage: Message = {
role: "assistant",
content: result.response,
diff --git a/frontend/app/connectors/page.tsx b/frontend/app/connectors/page.tsx
index 6221a87a5..28e6c8db4 100644
--- a/frontend/app/connectors/page.tsx
+++ b/frontend/app/connectors/page.tsx
@@ -3,6 +3,7 @@
import React, { useState } from "react";
import { CloudFile, UnifiedCloudPicker } from "@/components/cloud-picker";
import { useTask } from "@/contexts/task-context";
+import { apiClient } from "@/lib/api-client";
// CloudFile interface is now imported from the unified cloud picker
@@ -42,15 +43,12 @@ export default function ConnectorsPage() {
selected_files: selectedFiles.map((file) => file.id),
};
- const response = await fetch(`/api/connectors/${connector.type}/sync`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(syncBody),
- });
+ const response = await apiClient.post(
+ `/connectors/${connector.type}/sync`,
+ syncBody,
+ );
- const result = await response.json();
+ const result = response.data;
if (response.status === 201) {
const taskId = result.task_id;
@@ -65,7 +63,7 @@ export default function ConnectorsPage() {
status: "started",
});
}
- } else if (response.ok) {
+ } else if (response.status >= 200 && response.status < 300) {
setSyncResult(result);
} else {
console.error("Sync failed:", result.error);
diff --git a/frontend/app/health/collective_health/route.ts b/frontend/app/health/collective_health/route.ts
index 8968fd87c..4c32a3704 100644
--- a/frontend/app/health/collective_health/route.ts
+++ b/frontend/app/health/collective_health/route.ts
@@ -1,3 +1,4 @@
+import axios from "axios";
import { NextResponse } from "next/server";
interface PodStatus {
@@ -18,17 +19,24 @@ async function checkPodLiveness(url: string, timeout = 3000): Promise<boolean> {
const timeoutId = setTimeout(() => controller.abort(), timeout);
try {
- const response = await fetch(url, {
+ const response = await axios.get(url, {
signal: controller.signal,
- method: "GET",
+ timeout,
+ proxy: false,
+ responseType: "stream",
+ validateStatus: () => true,
});
-
- clearTimeout(timeoutId);
+ // Liveness depends only on the status line. Do not wait for a pod that
+ // keeps the response body open indefinitely.
+ if (response.data && typeof response.data.destroy === "function") {
+ response.data.destroy();
+ }
// Pod is alive if it responds (any status code means it's running)
return response.status < 500;
} catch {
- clearTimeout(timeoutId);
return false;
+ } finally {
+ clearTimeout(timeoutId);
}
}
diff --git a/frontend/app/providers.test.tsx b/frontend/app/providers.test.tsx
new file mode 100644
index 000000000..599182946
--- /dev/null
+++ b/frontend/app/providers.test.tsx
@@ -0,0 +1,27 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+describe("Providers fetch interceptor", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("adds the configured base path to same-origin API fetches", async () => {
+ const originalFetch = window.fetch;
+ const underlyingFetch = vi
+ .fn()
+ .mockResolvedValue(new Response("{}", { status: 200 }));
+
+ window.fetch = underlyingFetch as typeof window.fetch;
+ vi.stubEnv("NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ vi.resetModules();
+ await import("./providers");
+
+ await window.fetch("/api/langflow", { method: "POST" });
+
+ expect(underlyingFetch).toHaveBeenCalledWith("/openrag-fe/api/langflow", {
+ method: "POST",
+ });
+
+ window.fetch = originalFetch;
+ });
+});
diff --git a/frontend/app/providers.tsx b/frontend/app/providers.tsx
index da8cf2232..733a90343 100644
--- a/frontend/app/providers.tsx
+++ b/frontend/app/providers.tsx
@@ -2,13 +2,50 @@
import { QueryClientProvider } from "@tanstack/react-query";
import type * as React from "react";
import { getQueryClient } from "@/app/api/get-query-client";
+import { withFrontendBasePath } from "@/lib/frontend-base-path";
if (typeof window !== "undefined") {
const FETCH_PATCHED = Symbol.for("__fetch_patched__");
- if (!(window.fetch as any)[FETCH_PATCHED]) {
- const originalFetch = window.fetch;
- const patchedFetch = async (...args: Parameters<typeof fetch>) => {
- const response = await originalFetch(...args);
+ type MarkedFetch = typeof window.fetch & {
+ [FETCH_PATCHED]?: boolean;
+ };
+ const currentFetch = window.fetch as MarkedFetch;
+
+ if (!currentFetch[FETCH_PATCHED]) {
+ const originalFetch = window.fetch.bind(window);
+ const patchedFetch: typeof window.fetch = async (input, init) => {
+ let rewrittenInput = input;
+ const rawUrl =
+ input instanceof Request
+ ? input.url
+ : typeof input === "string" || input instanceof URL
+ ? input.toString()
+ : undefined;
+
+ if (rawUrl) {
+ try {
+ const url = new URL(rawUrl, window.location.origin);
+ if (
+ url.origin === window.location.origin &&
+ url.pathname.startsWith("/api/")
+ ) {
+ url.pathname = withFrontendBasePath(url.pathname);
+ const rewrittenUrl = `${url.pathname}${url.search}${url.hash}`;
+ rewrittenInput =
+ input instanceof Request
+ ? new Request(url.toString(), input)
+ : input instanceof URL
+ ? url
+ : input.startsWith("/")
+ ? rewrittenUrl
+ : url.toString();
+ }
+ } catch {
+ // Preserve the original request for malformed URLs.
+ }
+ }
+
+ const response = await originalFetch(rewrittenInput, init);
if (response.status === 401) {
try {
const clone = response.clone();
@@ -17,39 +54,38 @@ if (typeof window !== "undefined") {
const redirectUrl =
data.redirect_url || data.redirectUrl || data.redirect;
if (redirectUrl && typeof redirectUrl === "string") {
- // Validate redirectUrl to prevent open redirect
- let validatedUrl = "/login";
+ let validatedUrl = withFrontendBasePath("/login");
if (
redirectUrl.startsWith("/") &&
!redirectUrl.startsWith("//")
) {
- // Relative path - safe to use
- validatedUrl = redirectUrl;
+ validatedUrl = withFrontendBasePath(redirectUrl);
} else {
try {
const url = new URL(redirectUrl, location.origin);
if (url.origin === location.origin) {
- // Same-origin absolute URL - safe to use
- validatedUrl = redirectUrl;
+ url.pathname = withFrontendBasePath(url.pathname);
+ validatedUrl = url.toString();
}
- } catch (_e) {
- // Invalid URL, use default
+ } catch {
+ // Invalid URLs use the local login fallback.
}
}
window.location.href = validatedUrl;
}
}
- } catch (e) {
+ } catch (error) {
console.error(
"Failed to parse 401 response payload for redirect url:",
- e,
+ error,
);
}
}
return response;
};
- (patchedFetch as any)[FETCH_PATCHED] = true;
- window.fetch = patchedFetch as typeof fetch;
+
+ (patchedFetch as MarkedFetch)[FETCH_PATCHED] = true;
+ window.fetch = patchedFetch;
}
}
diff --git a/frontend/app/settings/[tab]/page.tsx b/frontend/app/settings/[tab]/page.tsx
index 9accd9bee..6e5b04161 100644
--- a/frontend/app/settings/[tab]/page.tsx
+++ b/frontend/app/settings/[tab]/page.tsx
@@ -1,4 +1,6 @@
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
+import axios from "axios";
+import { cookies, headers } from "next/headers";
import { redirect } from "next/navigation";
import { getQueryClient } from "@/app/api/get-query-client";
import {
@@ -6,7 +8,6 @@ import {
canAccessConnectorAccessTab,
canShowRbacGatedSettingsTab,
} from "@/lib/brand";
-import { fetchFromBackend } from "@/lib/fetch-server";
import { AgentSettingsSection } from "../_components/agent-settings-section";
import { ApiKeysSection } from "../_components/api-keys-section";
import { ConnectorAccessSection } from "../_components/connector-access-section";
@@ -30,18 +31,48 @@ function isValidTab(tab: string): tab is Tab {
}
async function getTabAuthContext() {
+ const backendHost = process.env.OPENRAG_BACKEND_HOST || "localhost";
+ const backendSSL = process.env.OPENRAG_BACKEND_SSL === "true";
+ const backendPort = process.env.OPENRAG_BACKEND_PORT || "8000";
+ const backendBaseUrl = `${backendSSL ? "https" : "http"}://${backendHost}:${backendPort}`;
+ const cookieStore = await cookies();
+ const incoming = await headers();
+
+ const jwtAuthHeader = (
+ process.env.OPENRAG_JWT_AUTH_HEADER || "Authorization"
+ ).toLowerCase();
+ const ibmCredentialsHeader = (
+ process.env.IBM_CREDENTIALS_HEADER || "X-IBM-LH-Credentials"
+ ).toLowerCase();
+ const forwardedHeaders: Record<string, string> = {
+ Cookie: cookieStore.toString(),
+ };
+ const authValue = incoming.get(jwtAuthHeader);
+ if (authValue) forwardedHeaders[jwtAuthHeader] = authValue;
+ const credentialsValue = incoming.get(ibmCredentialsHeader);
+ if (credentialsValue)
+ forwardedHeaders[ibmCredentialsHeader] = credentialsValue;
+
+ const requestConfig = {
+ headers: forwardedHeaders,
+ validateStatus: () => true,
+ };
const [authRes, meRes] = await Promise.allSettled([
- fetchFromBackend("auth/me"),
- fetchFromBackend("users/me"),
+ axios.get(`${backendBaseUrl}/auth/me`, requestConfig),
+ axios.get(`${backendBaseUrl}/users/me`, requestConfig),
]);
const authData =
- authRes.status === "fulfilled" && authRes.value.ok
- ? await authRes.value.json()
+ authRes.status === "fulfilled" &&
+ authRes.value.status >= 200 &&
+ authRes.value.status < 300
+ ? authRes.value.data
: {};
const meData =
- meRes.status === "fulfilled" && meRes.value.ok
- ? await meRes.value.json()
+ meRes.status === "fulfilled" &&
+ meRes.value.status >= 200 &&
+ meRes.value.status < 300
+ ? meRes.value.data
: {};
const permissions = new Set<string>(
@@ -59,6 +90,8 @@ async function getTabAuthContext() {
permissions,
rbacEnforced,
cloudContext,
+ backendBaseUrl,
+ forwardedHeaders,
};
}
@@ -80,6 +113,8 @@ export default async function SettingsTabPage({
permissions,
rbacEnforced,
cloudContext,
+ backendBaseUrl,
+ forwardedHeaders,
} = await getTabAuthContext();
const tabAccess = buildSettingsTabAccess({
@@ -118,9 +153,14 @@ export default async function SettingsTabPage({
await queryClient.prefetchQuery({
queryKey: ["settings"],
queryFn: async () => {
- const res = await fetchFromBackend("settings");
- if (!res.ok) throw new Error("Failed to fetch settings");
- return res.json();
+ const res = await axios.get(`${backendBaseUrl}/settings`, {
+ headers: forwardedHeaders,
+ validateStatus: () => true,
+ });
+ if (res.status < 200 || res.status >= 300) {
+ throw new Error("Failed to fetch settings");
+ }
+ return res.data;
},
});
} catch {
@@ -132,9 +172,14 @@ export default async function SettingsTabPage({
await queryClient.prefetchQuery({
queryKey: ["api-keys"],
queryFn: async () => {
- const res = await fetchFromBackend("keys");
- if (!res.ok) throw new Error("Failed to fetch api keys");
- return res.json();
+ const res = await axios.get(`${backendBaseUrl}/keys`, {
+ headers: forwardedHeaders,
+ validateStatus: () => true,
+ });
+ if (res.status < 200 || res.status >= 300) {
+ throw new Error("Failed to fetch api keys");
+ }
+ return res.data;
},
});
} catch {
diff --git a/frontend/app/settings/_components/agent-settings-section.tsx b/frontend/app/settings/_components/agent-settings-section.tsx
index e38bbe481..1e8a2fecb 100644
--- a/frontend/app/settings/_components/agent-settings-section.tsx
+++ b/frontend/app/settings/_components/agent-settings-section.tsx
@@ -26,6 +26,7 @@ import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { useRegisterDirty } from "@/contexts/unsaved-changes-context";
import { trackButton } from "@/lib/analytics";
+import { apiClient } from "@/lib/api-client";
import { DEFAULT_AGENT_SETTINGS, UI_CONSTANTS } from "@/lib/constants";
import { resolveLangflowEditUrl } from "@/lib/url-utils";
import { cn } from "@/lib/utils";
@@ -220,26 +221,23 @@ export function AgentSettingsSection() {
namespace: "settings",
});
- fetch("/api/reset-flow/retrieval", { method: "POST" })
- .then((res) =>
- res.text().then((text) => {
- const body = text ? JSON.parse(text) : {};
- if (!res.ok) {
- throw new Error(
- body.error ?? `HTTP ${res.status}: ${res.statusText}`,
- );
- }
- }),
- )
- .then(() =>
- // The flow reset above only replaces the Langflow graph. The system
- // prompt lives in a separate store, so restore must persist the
- // default there too, or it reverts on refresh while leaving Save
- // stuck enabled against it.
- updateSettingsMutation.mutateAsync({
- system_prompt: DEFAULT_AGENT_SETTINGS.system_prompt,
- }),
- )
+ apiClient
+ .post("/reset-flow/retrieval")
+ .then((res) => {
+ if (res.status < 200 || res.status >= 300) {
+ const body = res.data ?? {};
+ throw new Error(body.error ?? `HTTP ${res.status}`);
+ }
+ return (
+ // The flow reset above only replaces the Langflow graph. The system
+ // prompt lives in a separate store, so restore must persist the
+ // default there too, or it reverts on refresh while leaving Save
+ // stuck enabled against it.
+ updateSettingsMutation.mutateAsync({
+ system_prompt: DEFAULT_AGENT_SETTINGS.system_prompt,
+ })
+ );
+ })
.then(() => {
setSystemPrompt(DEFAULT_AGENT_SETTINGS.system_prompt);
setUserEdited(false);
diff --git a/frontend/app/settings/_components/connector-access-section.tsx b/frontend/app/settings/_components/connector-access-section.tsx
index 0f794e38d..06185d8f9 100644
--- a/frontend/app/settings/_components/connector-access-section.tsx
+++ b/frontend/app/settings/_components/connector-access-section.tsx
@@ -35,6 +35,7 @@ import { Input } from "@/components/ui/input";
import { type Status, StatusBadge } from "@/components/ui/status-badge";
import { Switch } from "@/components/ui/switch";
import { trackButton } from "@/lib/analytics";
+import { frontendUrl } from "@/lib/frontend-base-path";
interface OAuthCredentialGroup {
credentialKey: string;
@@ -403,7 +404,7 @@ export function ConnectorAccessSection() {
status: "not_connected",
type: group.testConnectorType,
},
- redirectUri: `${window.location.origin}/auth/callback`,
+ redirectUri: frontendUrl("/auth/callback"),
purpose: "test",
});
}}
diff --git a/frontend/app/settings/_components/connector-cards.tsx b/frontend/app/settings/_components/connector-cards.tsx
index 7543ed52f..c15dc02d5 100644
--- a/frontend/app/settings/_components/connector-cards.tsx
+++ b/frontend/app/settings/_components/connector-cards.tsx
@@ -16,6 +16,7 @@ import {
getConnectorDescriptor,
getConnectorDescriptors,
} from "@/lib/connectors/registry";
+import { frontendUrl } from "@/lib/frontend-base-path";
import ConnectorCard, { type Connector } from "./connector-card";
import ConnectorsSkeleton from "./connectors-skeleton";
@@ -69,7 +70,7 @@ export default function ConnectorCards() {
const handleConnect = async (connector: Connector) => {
connectMutation.mutate({
connector: connector as unknown as QueryConnector,
- redirectUri: `${window.location.origin}/auth/callback`,
+ redirectUri: frontendUrl("/auth/callback"),
});
};
diff --git a/frontend/app/settings/_components/ingest-settings-section.test.tsx b/frontend/app/settings/_components/ingest-settings-section.test.tsx
index 4219c1611..9eeff4c38 100644
--- a/frontend/app/settings/_components/ingest-settings-section.test.tsx
+++ b/frontend/app/settings/_components/ingest-settings-section.test.tsx
@@ -391,6 +391,19 @@ describe("IngestSettingsSection", () => {
}),
);
+ const input = await screen.findByRole("spinbutton", {
+ name: /chunk size/i,
+ });
+ expect(input).toHaveValue(500);
+
+ // The server-sync effect settles a tick after the value appears, so
+ // wait for it rather than asserting disabled against a transient render.
+ await waitFor(() => {
+ expect(
+ screen.getByRole("button", { name: /save changes/i }),
+ ).toBeDisabled();
+ });
+
server.use(
http.post("/api/reset-flow/ingest", () => HttpResponse.json({})),
http.post("/api/settings", () =>
@@ -412,19 +425,6 @@ describe("IngestSettingsSection", () => {
),
);
- const input = await screen.findByRole("spinbutton", {
- name: /chunk size/i,
- });
- expect(input).toHaveValue(500);
-
- // The server-sync effect settles a tick after the value appears, so
- // wait for it rather than asserting disabled against a transient render.
- await waitFor(() => {
- expect(
- screen.getByRole("button", { name: /save changes/i }),
- ).toBeDisabled();
- });
-
await userEvent.click(
await screen.findByRole("button", { name: /restore flow/i }),
);
diff --git a/frontend/app/settings/_components/ingest-settings-section.tsx b/frontend/app/settings/_components/ingest-settings-section.tsx
index 5931f8708..edc27de43 100644
--- a/frontend/app/settings/_components/ingest-settings-section.tsx
+++ b/frontend/app/settings/_components/ingest-settings-section.tsx
@@ -52,6 +52,7 @@ import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { useRegisterDirty } from "@/contexts/unsaved-changes-context";
import { trackButton } from "@/lib/analytics";
+import { apiClient } from "@/lib/api-client";
import {
DEFAULT_KNOWLEDGE_SETTINGS,
OCR_LANGUAGE_OPTIONS,
@@ -617,32 +618,30 @@ export function IngestSettingsSection() {
elementId: "restore-ingest-flow-button",
namespace: "settings",
});
- fetch("/api/reset-flow/ingest", { method: "POST" })
- .then((res) =>
- res.text().then((text) => {
- const body = text ? JSON.parse(text) : {};
- if (!res.ok) {
- throw new Error(
- body.error ?? `HTTP ${res.status}: ${res.statusText}`,
- );
- }
- }),
- )
- .then(() =>
- // The flow reset above only replaces the Langflow graph. The knowledge
- // settings (chunk size, OCR, etc.) live in a separate store, so restore
- // must persist the defaults there too, or the form shows defaults that
- // vanish on refresh while leaving Save stuck enabled against them.
- updateSettingsMutation.mutateAsync({
- chunk_size: DEFAULT_KNOWLEDGE_SETTINGS.chunk_size,
- chunk_overlap: DEFAULT_KNOWLEDGE_SETTINGS.chunk_overlap,
- table_structure: DEFAULT_KNOWLEDGE_SETTINGS.table_structure,
- ocr: DEFAULT_KNOWLEDGE_SETTINGS.ocr,
- ocr_languages: [...DEFAULT_KNOWLEDGE_SETTINGS.ocr_languages],
- picture_descriptions: DEFAULT_KNOWLEDGE_SETTINGS.picture_descriptions,
- disable_ingest_with_langflow: false,
- }),
- )
+ apiClient
+ .post("/reset-flow/ingest")
+ .then((res) => {
+ if (res.status < 200 || res.status >= 300) {
+ const body = res.data ?? {};
+ throw new Error(body.error ?? `HTTP ${res.status}`);
+ }
+ return (
+ // The flow reset above only replaces the Langflow graph. The knowledge
+ // settings (chunk size, OCR, etc.) live in a separate store, so restore
+ // must persist the defaults there too, or the form shows defaults that
+ // vanish on refresh while leaving Save stuck enabled against them.
+ updateSettingsMutation.mutateAsync({
+ chunk_size: DEFAULT_KNOWLEDGE_SETTINGS.chunk_size,
+ chunk_overlap: DEFAULT_KNOWLEDGE_SETTINGS.chunk_overlap,
+ table_structure: DEFAULT_KNOWLEDGE_SETTINGS.table_structure,
+ ocr: DEFAULT_KNOWLEDGE_SETTINGS.ocr,
+ ocr_languages: [...DEFAULT_KNOWLEDGE_SETTINGS.ocr_languages],
+ picture_descriptions:
+ DEFAULT_KNOWLEDGE_SETTINGS.picture_descriptions,
+ disable_ingest_with_langflow: false,
+ })
+ );
+ })
.then(() => {
setChunkSize(DEFAULT_KNOWLEDGE_SETTINGS.chunk_size);
setChunkOverlap(DEFAULT_KNOWLEDGE_SETTINGS.chunk_overlap);
diff --git a/frontend/app/settings/_components/model-providers.test.ts b/frontend/app/settings/_components/model-providers.test.ts
new file mode 100644
index 000000000..94a3df035
--- /dev/null
+++ b/frontend/app/settings/_components/model-providers.test.ts
@@ -0,0 +1,20 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+});
+
+describe("providerDialogCloseUrl", () => {
+ it("removes the frontend base path before returning a router URL", async () => {
+ vi.stubEnv("NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ const { providerDialogCloseUrl } = await import("./model-providers");
+
+ expect(
+ providerDialogCloseUrl(
+ "/openrag-fe/settings/providers",
+ new URLSearchParams("tab=all"),
+ ),
+ ).toBe("/settings/providers?tab=all");
+ });
+});
diff --git a/frontend/app/settings/_components/model-providers.tsx b/frontend/app/settings/_components/model-providers.tsx
index 6c55ba526..58644eb6f 100644
--- a/frontend/app/settings/_components/model-providers.tsx
+++ b/frontend/app/settings/_components/model-providers.tsx
@@ -10,6 +10,7 @@ import {
} from "@/components/models/model-helpers";
import { useProviderHealth } from "@/components/provider-health-banner";
import { useAuth } from "@/contexts/auth-context";
+import { withoutFrontendBasePath } from "@/lib/frontend-base-path";
import AnthropicSettingsDialog from "./anthropic-settings-dialog";
import ModelProviderCard from "./model-provider-card";
import OllamaSettingsDialog from "./ollama-settings-dialog";
@@ -26,6 +27,16 @@ const BESPOKE_DIALOG_PROVIDERS = new Set<ModelProvider>([
"watsonx",
]);
+export function providerDialogCloseUrl(
+ pathname: string,
+ params: URLSearchParams,
+): string {
+ const appPathname = withoutFrontendBasePath(pathname);
+ return params.toString()
+ ? `${appPathname}?${params.toString()}`
+ : appPathname;
+}
+
export const ModelProviders = () => {
const { isAuthenticated, isNoAuthMode } = useAuth();
const searchParams = useSearchParams();
@@ -73,10 +84,7 @@ export const ModelProviders = () => {
// Remove search param from URL
const params = new URLSearchParams(searchParams.toString());
params.delete("setup");
- const newUrl = params.toString()
- ? `${window.location.pathname}?${params.toString()}`
- : window.location.pathname;
- router.replace(newUrl);
+ router.replace(providerDialogCloseUrl(window.location.pathname, params));
};
const currentLlmProvider =
diff --git a/frontend/app/settings/_components/s3-settings-dialog.tsx b/frontend/app/settings/_components/s3-settings-dialog.tsx
index 36579a307..f209940d5 100644
--- a/frontend/app/settings/_components/s3-settings-dialog.tsx
+++ b/frontend/app/settings/_components/s3-settings-dialog.tsx
@@ -15,6 +15,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { apiClient } from "@/lib/api-client";
import { type S3FormData, S3SettingsForm } from "./s3-settings-form";
interface S3SettingsDialogProps {
@@ -83,11 +84,12 @@ export default function S3SettingsDialog({
connection_id: defaults?.connection_id ?? undefined,
});
- const res = await fetch(
- `/api/connectors/aws_s3/${result.connection_id}/buckets`,
+ const res = await apiClient.get(
+ `/connectors/aws_s3/${result.connection_id}/buckets`,
);
- const json = await res.json();
- if (!res.ok) throw new Error(json.error || "Failed to list buckets");
+ const json = res.data;
+ if (res.status < 200 || res.status >= 300)
+ throw new Error(json.error || "Failed to list buckets");
const fetchedBuckets: string[] = json.buckets;
setBuckets(fetchedBuckets);
@@ -115,8 +117,8 @@ export default function S3SettingsDialog({
const latestDefaults = await queryClient.fetchQuery({
queryKey: ["s3-defaults"],
queryFn: async () => {
- const res = await fetch("/api/connectors/aws_s3/defaults");
- return res.json();
+ const res = await apiClient.get("/connectors/aws_s3/defaults");
+ return res.data;
},
staleTime: 0,
});
diff --git a/frontend/app/upload/[provider]/page.tsx b/frontend/app/upload/[provider]/page.tsx
index 3cd432749..95e52ca2e 100644
--- a/frontend/app/upload/[provider]/page.tsx
+++ b/frontend/app/upload/[provider]/page.tsx
@@ -19,6 +19,7 @@ import {
import { useTask } from "@/contexts/task-context";
import { useSessionIngestSettings } from "@/hooks/useSessionIngestSettings";
import { trackProcessFailure, trackStartProcess } from "@/lib/analytics";
+import { apiClient } from "@/lib/api-client";
import { getConnectorDescriptor } from "@/lib/connectors/registry";
interface ConnectorDuplicateCheckResponse {
@@ -166,33 +167,26 @@ export default function UploadProviderPage() {
setIsCheckingDuplicates(true);
try {
- const checkResponse = await fetch(
- `/api/connectors/${connector.type}/check-duplicates`,
+ const checkResponse = await apiClient.post(
+ `/connectors/${connector.type}/check-duplicates`,
{
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- connection_id: connector.connectionId,
- selected_files: selectedFiles.map((file) => ({
- id: file.id,
- name: file.name,
- mimeType: file.mimeType,
- downloadUrl: file.downloadUrl,
- size: file.size,
- isFolder: file.isFolder,
- })),
- }),
+ connection_id: connector.connectionId,
+ selected_files: selectedFiles.map((file) => ({
+ id: file.id,
+ name: file.name,
+ mimeType: file.mimeType,
+ downloadUrl: file.downloadUrl,
+ size: file.size,
+ isFolder: file.isFolder,
+ })),
},
);
- if (!checkResponse.ok) {
+ if (checkResponse.status < 200 || checkResponse.status >= 300) {
throw new Error(`Duplicate check failed: ${checkResponse.statusText}`);
}
- const checkData =
- (await checkResponse.json()) as ConnectorDuplicateCheckResponse;
+ const checkData = checkResponse.data as ConnectorDuplicateCheckResponse;
const duplicateNames = checkData.duplicate_names || [];
const duplicateCount =
typeof checkData.duplicate_count === "number"
diff --git a/frontend/components/cloud-picker/provider-handlers.ts b/frontend/components/cloud-picker/provider-handlers.ts
index 62c5707fe..967f5eaae 100644
--- a/frontend/components/cloud-picker/provider-handlers.ts
+++ b/frontend/components/cloud-picker/provider-handlers.ts
@@ -1,5 +1,6 @@
"use client";
+import axios from "axios";
import { SharePointV8Handler } from "./sharepoint-v8-handler";
import {
CloudFile,
@@ -114,16 +115,20 @@ class GoogleDriveHandler {
files.map(async (file) => {
if (!file.size && !file.isFolder) {
try {
- const response = await fetch(
+ const response = await axios.get<{
+ size?: string;
+ modifiedTime?: string;
+ }>(
`https://www.googleapis.com/drive/v3/files/${file.id}?fields=size,modifiedTime`,
{
headers: {
Authorization: `Bearer ${this.accessToken}`,
},
+ validateStatus: () => true,
},
);
- if (response.ok) {
- const fileDetails = await response.json();
+ if (response.status >= 200 && response.status < 300) {
+ const fileDetails = response.data;
return {
...file,
size: fileDetails.size
@@ -225,11 +230,12 @@ class OneDriveHandler {
if (driveId && itemId) {
try {
const url = `https://graph.microsoft.com/v1.0/drives/${driveId}/items/${itemId}`;
- const res = await fetch(url, {
+ const res = await axios.get(url, {
headers: { Authorization: `Bearer ${this.accessToken}` },
+ validateStatus: () => true,
});
- if (res.ok) {
- const meta = await res.json();
+ if (res.status >= 200 && res.status < 300) {
+ const meta = res.data;
let mimeType = meta.file?.mimeType;
if (!mimeType && meta.name) {
@@ -271,7 +277,9 @@ class OneDriveHandler {
console.warn(
"Graph API metadata fetch failed:",
res.status,
- await res.text(),
+ typeof res.data === "string"
+ ? res.data
+ : JSON.stringify(res.data),
);
}
} catch (e) {
diff --git a/frontend/components/connectors/shared-bucket-view.tsx b/frontend/components/connectors/shared-bucket-view.tsx
index 57bcaf33c..5c6c80147 100644
--- a/frontend/components/connectors/shared-bucket-view.tsx
+++ b/frontend/components/connectors/shared-bucket-view.tsx
@@ -14,6 +14,7 @@ import { Button } from "@/components/ui/button";
import { useAuth } from "@/contexts/auth-context";
import { useSessionIngestSettings } from "@/hooks/useSessionIngestSettings";
import { trackProcessFailure, trackStartProcess } from "@/lib/analytics";
+import { apiClient } from "@/lib/api-client";
interface BucketDuplicateFile {
id: string;
@@ -261,24 +262,19 @@ export function SharedBucketView({
setIsCheckingDuplicates(true);
try {
- const checkResponse = await fetch(
- `/api/connectors/${connector.type}/check-duplicates`,
+ const checkResponse = await apiClient.post(
+ `/connectors/${connector.type}/check-duplicates`,
{
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- connection_id: connector.connectionId,
- bucket_filter: Array.from(selectedBuckets),
- }),
+ connection_id: connector.connectionId,
+ bucket_filter: Array.from(selectedBuckets),
},
);
- if (!checkResponse.ok) {
+ if (checkResponse.status < 200 || checkResponse.status >= 300) {
throw new Error(`Duplicate check failed: ${checkResponse.statusText}`);
}
- const checkData =
- (await checkResponse.json()) as BucketDuplicateCheckResponse;
+ const checkData = checkResponse.data as BucketDuplicateCheckResponse;
const duplicateNames = checkData.duplicate_names || [];
const duplicateCount =
typeof checkData.duplicate_count === "number"
diff --git a/frontend/components/dev-role-toggle.tsx b/frontend/components/dev-role-toggle.tsx
index 689d26150..a007ba361 100644
--- a/frontend/components/dev-role-toggle.tsx
+++ b/frontend/components/dev-role-toggle.tsx
@@ -9,6 +9,7 @@ import {
} from "@/app/api/queries/useGetConnectorsQuery";
import { useAuth } from "@/contexts/auth-context";
import { useBrand } from "@/contexts/brand-context";
+import { apiClient } from "@/lib/api-client";
import { IBM_THEME_DEV } from "@/lib/brand";
function parseApiError(
@@ -46,20 +47,15 @@ export function DevRoleToggle() {
const mutation = useMutation({
mutationFn: async (role: string) => {
- const response = await fetch("/api/users/me/dev-role", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ role }),
- credentials: "include",
- });
- if (!response.ok) {
- const result = (await response.json().catch(() => ({}))) as Record<
- string,
- unknown
- >;
+ const response = await apiClient.post<{ role?: string }>(
+ "/users/me/dev-role",
+ { role },
+ );
+ if (response.status < 200 || response.status >= 300) {
+ const result = (response.data ?? {}) as Record<string, unknown>;
throw new Error(parseApiError(result, response.status));
}
- return response.json() as Promise<{ role?: string }>;
+ return response.data;
},
onSuccess: async (data) => {
await Promise.all([
diff --git a/frontend/components/file-browser-dialog.test.tsx b/frontend/components/file-browser-dialog.test.tsx
index 32a7c90fd..da1e189f9 100644
--- a/frontend/components/file-browser-dialog.test.tsx
+++ b/frontend/components/file-browser-dialog.test.tsx
@@ -1,6 +1,8 @@
+import { HttpResponse, http } from "msw";
import { toast } from "sonner";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { IngestSettings } from "@/components/cloud-picker/types";
+import { server } from "@/test-utils/msw/server";
import {
fireEvent,
renderWithProviders,
@@ -57,7 +59,6 @@ describe("FileBrowserDialog ingest validation", () => {
beforeEach(() => {
mutateAsync.mockReset();
vi.mocked(toast.error).mockClear();
- global.fetch = vi.fn();
});
it("blocks ingest with a toast when chunk overlap is not below chunk size", () => {
@@ -69,7 +70,6 @@ describe("FileBrowserDialog ingest validation", () => {
expect(toast.error).toHaveBeenCalledWith("Could not start ingest", {
description: "Chunk overlap must be less than chunk size",
});
- expect(global.fetch).not.toHaveBeenCalled();
expect(mutateAsync).not.toHaveBeenCalled();
});
});
@@ -94,7 +94,11 @@ describe("FileBrowserDialog duplicate-check failures", () => {
}
it("ingests nothing and says so when the check request rejects", async () => {
- global.fetch = vi.fn().mockRejectedValue(new Error("network down"));
+ server.use(
+ http.post("/api/connectors/ibm_cos/check-duplicates", () =>
+ HttpResponse.error(),
+ ),
+ );
ingest();
@@ -110,9 +114,12 @@ describe("FileBrowserDialog duplicate-check failures", () => {
});
it("ingests nothing and says so when the check returns an error status", async () => {
- global.fetch = vi
- .fn()
- .mockResolvedValue({ ok: false, statusText: "Gateway Timeout" });
+ server.use(
+ http.post(
+ "/api/connectors/ibm_cos/check-duplicates",
+ () => new HttpResponse(null, { status: 504 }),
+ ),
+ );
ingest();
@@ -121,10 +128,11 @@ describe("FileBrowserDialog duplicate-check failures", () => {
});
it("still ingests when the check succeeds and finds nothing", async () => {
- global.fetch = vi.fn().mockResolvedValue({
- ok: true,
- json: async () => ({ duplicate_names: [], duplicate_count: 0 }),
- });
+ server.use(
+ http.post("/api/connectors/ibm_cos/check-duplicates", () =>
+ HttpResponse.json({ duplicate_names: [], duplicate_count: 0 }),
+ ),
+ );
ingest();
diff --git a/frontend/components/file-browser-dialog.tsx b/frontend/components/file-browser-dialog.tsx
index 189281e2a..e40e0d8e8 100644
--- a/frontend/components/file-browser-dialog.tsx
+++ b/frontend/components/file-browser-dialog.tsx
@@ -12,6 +12,7 @@ import {
type IngestSettings,
validateIngestSettingsOrToast,
} from "@/components/cloud-picker/types";
+import { apiClient } from "@/lib/api-client";
import { formatFileSize } from "@/lib/file-format";
import { DuplicateHandlingDialog } from "./duplicate-handling-dialog";
import { Badge } from "./ui/badge";
@@ -207,24 +208,16 @@ export function FileBrowserDialog({
setIsCheckingDuplicates(true);
try {
- const checkResponse = await fetch(
- `/api/connectors/${connectorType}/check-duplicates`,
- {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- connection_id: connectionId,
- selected_files: filesPayload,
- }),
- },
+ const checkResponse = await apiClient.post(
+ `/connectors/${connectorType}/check-duplicates`,
+ { connection_id: connectionId, selected_files: filesPayload },
);
- if (!checkResponse.ok) {
+ if (checkResponse.status < 200 || checkResponse.status >= 300) {
throw new Error(`Duplicate check failed: ${checkResponse.statusText}`);
}
- const checkData =
- (await checkResponse.json()) as FileBrowserDuplicateCheckResponse;
+ const checkData = checkResponse.data as FileBrowserDuplicateCheckResponse;
const duplicateNames = checkData.duplicate_names || [];
const duplicateCount =
typeof checkData.duplicate_count === "number"
diff --git a/frontend/components/knowledge-dropdown.tsx b/frontend/components/knowledge-dropdown.tsx
index e90ccf6c9..3f453e3bd 100644
--- a/frontend/components/knowledge-dropdown.tsx
+++ b/frontend/components/knowledge-dropdown.tsx
@@ -43,6 +43,7 @@ import {
trackProcessFailure,
trackStartProcess,
} from "@/lib/analytics";
+import { apiClient } from "@/lib/api-client";
import {
getConnectorDescriptor,
getConnectorDescriptors,
@@ -164,14 +165,14 @@ export function KnowledgeDropdown() {
// Check upload batch size and bucket connector availability in parallel
const [uploadOptionsRes, ...bucketResponses] = await Promise.all([
- fetch("/api/upload_options"),
+ apiClient.get("/upload_options"),
...bucketDescriptors.map((d) =>
- fetch(`/api/connectors/${d.connectorType}/defaults`),
+ apiClient.get(`/connectors/${d.connectorType}/defaults`),
),
]);
- if (uploadOptionsRes.ok) {
- const uploadOptionsData = await uploadOptionsRes.json();
+ if (uploadOptionsRes.status >= 200 && uploadOptionsRes.status < 300) {
+ const uploadOptionsData = uploadOptionsRes.data;
if (
typeof uploadOptionsData.upload_batch_size === "number" &&
uploadOptionsData.upload_batch_size > 0
@@ -184,8 +185,8 @@ export function KnowledgeDropdown() {
await Promise.all(
bucketResponses.map(async (res, i) => {
const descriptor = bucketDescriptors[i];
- if (!res.ok) return;
- const data = await res.json();
+ if (res.status < 200 || res.status >= 300) return;
+ const data = res.data;
// Generic predicate: connection_id set OR any *_set boolean is true.
const anySetFlag = Object.entries(data).some(
([k, v]) => k.endsWith("_set") && v === true,
@@ -198,9 +199,9 @@ export function KnowledgeDropdown() {
setBucketConnectorConfigured(configured);
// Check cloud connectors
- const connectorsRes = await fetch("/api/connectors");
- if (connectorsRes.ok) {
- const connectorsResult = await connectorsRes.json();
+ const connectorsRes = await apiClient.get("/connectors");
+ if (connectorsRes.status >= 200 && connectorsRes.status < 300) {
+ const connectorsResult = connectorsRes.data;
// Bucket connector availability mirrors the backend `is_available()`
// gate (IBM auth, or the dev flag for Azure Blob), so the dropdown
@@ -245,10 +246,12 @@ export function KnowledgeDropdown() {
await Promise.all(
availableTypes.map(async (type) => {
try {
- const statusRes = await fetch(`/api/connectors/${type}/status`);
- if (!statusRes.ok) return;
+ const statusRes = await apiClient.get(
+ `/connectors/${type}/status`,
+ );
+ if (statusRes.status < 200 || statusRes.status >= 300) return;
- const statusData = await statusRes.json();
+ const statusData = statusRes.data;
const connections = statusData.connections || [];
const activeConnection = connections.find(
(conn: { is_active: boolean; connection_id: string }) =>
@@ -259,11 +262,11 @@ export function KnowledgeDropdown() {
connectorInfo[type].connected = true;
try {
- const tokenRes = await fetch(
- `/api/connectors/${type}/token?connection_id=${activeConnection.connection_id}`,
+ const tokenRes = await apiClient.get(
+ `/connectors/${type}/token?connection_id=${activeConnection.connection_id}`,
);
- if (tokenRes.ok) {
- const tokenData = await tokenRes.json();
+ if (tokenRes.status >= 200 && tokenRes.status < 300) {
+ const tokenData = tokenRes.data;
if (tokenData.access_token) {
connectorInfo[type].hasToken = true;
}
@@ -743,15 +746,11 @@ export function KnowledgeDropdown() {
});
try {
- const response = await fetch("/api/upload_path", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ path: folderPath }),
+ const response = await apiClient.post("/upload_path", {
+ path: folderPath,
});
- const result = await response.json();
+ const result = response.data;
if (response.status === 201) {
const taskId = result.task_id || result.id;
@@ -764,7 +763,7 @@ export function KnowledgeDropdown() {
setFolderPath("");
// Refetch tasks to show the new task
refetchTasks();
- } else if (response.ok) {
+ } else if (response.status >= 200 && response.status < 300) {
setFolderPath("");
// Refetch tasks even for direct uploads in case tasks were created
refetchTasks();
diff --git a/frontend/components/models/watsonx-space-select.tsx b/frontend/components/models/watsonx-space-select.tsx
index 45e0d9d9e..d6ad13886 100644
--- a/frontend/components/models/watsonx-space-select.tsx
+++ b/frontend/components/models/watsonx-space-select.tsx
@@ -17,6 +17,7 @@ import {
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
+import { apiClient } from "@/lib/api-client";
import { cn } from "@/lib/utils";
import { WATSONX_TLS_DISABLED_VALUES } from "./watsonx-tls-settings";
@@ -126,20 +127,19 @@ export function WatsonxSpaceSelect({
ssl_verify: sslVerify,
}).filter(([, credentialValue]) => credentialValue !== ""),
);
- const response = await fetch("/api/models/watsonx_onprem/spaces", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
+ const response = await apiClient.post(
+ "/models/watsonx_onprem/spaces",
+ {
credentials: submittedCredentials,
auth_method: authMethod,
- }),
- signal: controller.signal,
- });
- const result = (await response.json()) as {
+ },
+ { signal: controller.signal },
+ );
+ const result = response.data as {
spaces?: WatsonxSpace[];
error?: string;
};
- if (!response.ok) {
+ if (response.status < 200 || response.status >= 300) {
throw new Error(result.error || "Could not load deployment spaces");
}
dispatch({ type: "loaded", spaces: result.spaces ?? [] });
diff --git a/frontend/components/user-nav.tsx b/frontend/components/user-nav.tsx
index e72f4e62a..5f4e95cba 100644
--- a/frontend/components/user-nav.tsx
+++ b/frontend/components/user-nav.tsx
@@ -13,6 +13,8 @@ import {
import { useAuth } from "@/contexts/auth-context";
import { useIsCloudBrand } from "@/contexts/brand-context";
import { useUnsavedChangesGuard } from "@/contexts/unsaved-changes-context";
+import { apiClient } from "@/lib/api-client";
+import { withFrontendBasePath } from "@/lib/frontend-base-path";
import { cn } from "@/lib/utils";
import ThemeButtons from "./theme-switcher-buttons";
@@ -33,11 +35,11 @@ export function UserNav() {
const performLogout = async () => {
if (isCloudBrand) {
try {
- await fetch("/api/auth/logout", { method: "POST" });
+ await apiClient.post("/auth/logout");
} catch {
// Best-effort server cleanup; redirect regardless.
}
- window.location.href = "/logout";
+ window.location.href = withFrontendBasePath("/logout");
return;
}
await logout();
diff --git a/frontend/contexts/auth-context.tsx b/frontend/contexts/auth-context.tsx
index ac405a902..a764468f3 100644
--- a/frontend/contexts/auth-context.tsx
+++ b/frontend/contexts/auth-context.tsx
@@ -8,8 +8,10 @@ import React, {
useEffect,
useState,
} from "react";
+import { apiClient } from "@/lib/api-client";
import { hasRbacPermission } from "@/lib/brand";
import type { RunMode } from "@/lib/constants";
+import { frontendUrl } from "@/lib/frontend-base-path";
import { encodeBase64 } from "@/lib/utils";
export interface User {
@@ -84,15 +86,15 @@ export function AuthProvider({ children }: AuthProviderProps) {
const checkAuth = useCallback(async () => {
setIsLoading(true);
try {
- const response = await fetch("/api/auth/me");
+ const response = await apiClient.get("/auth/me");
// If we can't reach the backend, keep loading
- if (!response.ok && (response.status === 0 || response.status >= 500)) {
+ if (response.status === 0 || response.status >= 500) {
setTimeout(checkAuth, 2000);
return;
}
- const data = await response.json();
+ const data = response.data;
if (data.version) setVersion(data.version);
if (data.run_mode) setRunMode(data.run_mode);
@@ -133,21 +135,16 @@ export function AuthProvider({ children }: AuthProviderProps) {
}
// Use the correct auth callback URL, not connectors callback
- const redirectUri = `${window.location.origin}/auth/callback`;
+ const redirectUri = frontendUrl("/auth/callback");
- fetch("/api/auth/init", {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
+ apiClient
+ .post("/auth/init", {
connector_type: "google_drive",
purpose: "app_auth",
name: "App Authentication",
redirect_uri: redirectUri,
- }),
- })
- .then((response) => response.json())
+ })
+ .then((response) => response.data)
.then((result) => {
if (result.oauth_config) {
// Store that this is for app authentication
@@ -158,7 +155,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
const state = isIbmAuthMode
? encodeBase64(
- `id=${result.connection_id}&return=${window.location.origin}/auth/callback`,
+ `id=${result.connection_id}&return=${frontendUrl("/auth/callback")}`,
)
: result.connection_id;
@@ -182,14 +179,13 @@ export function AuthProvider({ children }: AuthProviderProps) {
};
const loginWithIbm = async (username: string, password: string) => {
- const response = await fetch("/api/auth/ibm/login", {
- method: "POST",
+ const response = await apiClient.post("/auth/ibm/login", undefined, {
headers: {
Authorization: "Basic " + btoa(username + ":" + password),
},
});
- if (!response.ok) {
- const data = await response.json().catch(() => ({}));
+ if (response.status < 200 || response.status >= 300) {
+ const data = response.data || {};
throw new Error(data.detail || "Login failed");
}
await checkAuth();
@@ -201,9 +197,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
}
try {
- await fetch("/api/auth/logout", {
- method: "POST",
- });
+ await apiClient.post("/auth/logout");
setUser(null);
} catch (error) {
console.error("Logout failed:", error);
@@ -233,12 +227,12 @@ export function AuthProvider({ children }: AuthProviderProps) {
const fetchPermissions = useCallback(async () => {
try {
- const r = await fetch("/api/users/me");
- if (!r.ok) {
+ const r = await apiClient.get("/users/me");
+ if (r.status < 200 || r.status >= 300) {
resetPermissionState();
return;
}
- const data = await r.json();
+ const data = r.data;
const perms: string[] = Array.isArray(data?.permissions)
? data.permissions
: [];
@@ -272,9 +266,9 @@ export function AuthProvider({ children }: AuthProviderProps) {
const fetchOnboardingStatus = useCallback(async () => {
try {
- const r = await fetch("/api/onboarding-status");
- if (!r.ok) return;
- const data = await r.json();
+ const r = await apiClient.get("/onboarding-status");
+ if (r.status < 200 || r.status >= 300) return;
+ const data = r.data;
setIsOnboarded(Boolean(data?.onboarded));
const step = data?.current_step;
setOnboardingStep(
diff --git a/frontend/enhancements/connectors/azure-blob/settings-dialog.tsx b/frontend/enhancements/connectors/azure-blob/settings-dialog.tsx
index a172d44b9..aae8d4c6a 100644
--- a/frontend/enhancements/connectors/azure-blob/settings-dialog.tsx
+++ b/frontend/enhancements/connectors/azure-blob/settings-dialog.tsx
@@ -1,6 +1,7 @@
"use client";
import { useQueryClient } from "@tanstack/react-query";
+import axios from "axios";
import { useEffect, useRef, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -12,6 +13,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { apiClient } from "@/lib/api-client";
import AzureBlobIcon from "./icon";
import { type AzureBlobFormData, AzureBlobSettingsForm } from "./settings-form";
import { useAzureBlobConfigureMutation } from "./useAzureBlobConfigureMutation";
@@ -97,21 +99,21 @@ export default function AzureBlobSettingsDialog({
// Validate credentials + list containers WITHOUT persisting. Saving is
// reserved for the Save button (onSubmit), so testing never creates or
// mutates the connection or clobbers the stored container selection.
- const res = await fetch("/api/connectors/azure_blob/test", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- signal: controller.signal,
- body: JSON.stringify({
+ const res = await apiClient.post(
+ "/connectors/azure_blob/test",
+ {
auth_mode: data.auth_mode,
connection_string: data.connection_string || undefined,
account_name: data.account_name || undefined,
account_key: data.account_key || undefined,
endpoint: data.endpoint || undefined,
connection_id: defaults?.connection_id ?? undefined,
- }),
- });
- const json = await res.json();
- if (!res.ok) throw new Error(json.error || "Failed to list containers");
+ },
+ { signal: controller.signal },
+ );
+ const json = res.data;
+ if (res.status < 200 || res.status >= 300)
+ throw new Error(json.error || "Failed to list containers");
const fetched: string[] = json.containers;
setContainers(fetched);
@@ -120,7 +122,12 @@ export default function AzureBlobSettingsDialog({
} catch (err: unknown) {
// Ignore cancellations — they are intentional (dialog closed or new test
// started) and must not surface an error message to the user.
- if (err instanceof DOMException && err.name === "AbortError") return;
+ if (
+ (err instanceof DOMException && err.name === "AbortError") ||
+ axios.isCancel(err)
+ ) {
+ return;
+ }
setContainersError(
err instanceof Error ? err.message : "Connection failed",
);
@@ -149,8 +156,8 @@ export default function AzureBlobSettingsDialog({
const latestDefaults = await queryClient.fetchQuery({
queryKey: ["azure-blob-defaults"],
queryFn: async () => {
- const res = await fetch("/api/connectors/azure_blob/defaults");
- return res.json();
+ const res = await apiClient.get("/connectors/azure_blob/defaults");
+ return res.data;
},
staleTime: 0,
});
diff --git a/frontend/enhancements/connectors/azure-blob/useAzureBlobConfigureMutation.ts b/frontend/enhancements/connectors/azure-blob/useAzureBlobConfigureMutation.ts
index 4120ded90..02efa7b0b 100644
--- a/frontend/enhancements/connectors/azure-blob/useAzureBlobConfigureMutation.ts
+++ b/frontend/enhancements/connectors/azure-blob/useAzureBlobConfigureMutation.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface AzureBlobConfigurePayload {
auth_mode: "connection_string" | "account_key";
@@ -15,13 +16,10 @@ export interface AzureBlobConfigurePayload {
}
async function configureAzureBlob(payload: AzureBlobConfigurePayload) {
- const res = await fetch("/api/connectors/azure_blob/configure", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(payload),
- });
- const data = await res.json();
- if (!res.ok) throw new Error(data.error || "Failed to configure Azure Blob");
+ const res = await apiClient.post("/connectors/azure_blob/configure", payload);
+ const data = res.data ?? {};
+ if (res.status < 200 || res.status >= 300)
+ throw new Error(data.error || "Failed to configure Azure Blob");
return data as { connection_id: string; status: string };
}
diff --git a/frontend/enhancements/connectors/azure-blob/useAzureBlobContainerStatusQuery.ts b/frontend/enhancements/connectors/azure-blob/useAzureBlobContainerStatusQuery.ts
index 82e36b027..0c634510b 100644
--- a/frontend/enhancements/connectors/azure-blob/useAzureBlobContainerStatusQuery.ts
+++ b/frontend/enhancements/connectors/azure-blob/useAzureBlobContainerStatusQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface AzureBlobContainerStatus {
name: string;
@@ -9,15 +10,14 @@ export interface AzureBlobContainerStatus {
async function fetchAzureBlobContainerStatus(
connectionId: string,
): Promise<AzureBlobContainerStatus[]> {
- const res = await fetch(
- `/api/connectors/azure_blob/${connectionId}/container-status`,
+ const res = await apiClient.get<{ containers: AzureBlobContainerStatus[] }>(
+ `/connectors/azure_blob/${connectionId}/container-status`,
);
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
+ if (res.status < 200 || res.status >= 300) {
+ const err = (res.data ?? {}) as { error?: string };
throw new Error(err.error || "Failed to fetch container status");
}
- const data = await res.json();
- return data.containers as AzureBlobContainerStatus[];
+ return res.data.containers;
}
export function useAzureBlobContainerStatusQuery(
diff --git a/frontend/enhancements/connectors/azure-blob/useAzureBlobDefaultsQuery.ts b/frontend/enhancements/connectors/azure-blob/useAzureBlobDefaultsQuery.ts
index eb9387f6c..2227d9f63 100644
--- a/frontend/enhancements/connectors/azure-blob/useAzureBlobDefaultsQuery.ts
+++ b/frontend/enhancements/connectors/azure-blob/useAzureBlobDefaultsQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface AzureBlobDefaults {
connection_string_set: boolean;
@@ -11,9 +12,12 @@ export interface AzureBlobDefaults {
}
async function fetchAzureBlobDefaults(): Promise<AzureBlobDefaults> {
- const res = await fetch("/api/connectors/azure_blob/defaults");
- if (!res.ok) throw new Error("Failed to fetch Azure Blob defaults");
- return res.json();
+ const res = await apiClient.get<AzureBlobDefaults>(
+ "/connectors/azure_blob/defaults",
+ );
+ if (res.status < 200 || res.status >= 300)
+ throw new Error("Failed to fetch Azure Blob defaults");
+ return res.data;
}
export function useAzureBlobDefaultsQuery(options?: { enabled?: boolean }) {
diff --git a/frontend/enhancements/connectors/ibm-cos/settings-dialog.tsx b/frontend/enhancements/connectors/ibm-cos/settings-dialog.tsx
index dc9a90308..b557af87e 100644
--- a/frontend/enhancements/connectors/ibm-cos/settings-dialog.tsx
+++ b/frontend/enhancements/connectors/ibm-cos/settings-dialog.tsx
@@ -12,6 +12,7 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { apiClient } from "@/lib/api-client";
import IBMCOSIcon from "./icon";
import { type IBMCOSFormData, IBMCOSSettingsForm } from "./settings-form";
import { useIBMCOSConfigureMutation } from "./useIBMCOSConfigureMutation";
@@ -80,11 +81,12 @@ export default function IBMCOSSettingsDialog({
});
// Then list buckets using the connection
- const res = await fetch(
- `/api/connectors/ibm_cos/${result.connection_id}/buckets`,
+ const res = await apiClient.get(
+ `/connectors/ibm_cos/${result.connection_id}/buckets`,
);
- const json = await res.json();
- if (!res.ok) throw new Error(json.error || "Failed to list buckets");
+ const json = res.data;
+ if (res.status < 200 || res.status >= 300)
+ throw new Error(json.error || "Failed to list buckets");
const fetchedBuckets: string[] = json.buckets;
setBuckets(fetchedBuckets);
@@ -115,8 +117,8 @@ export default function IBMCOSSettingsDialog({
const latestDefaults = await queryClient.fetchQuery({
queryKey: ["ibm-cos-defaults"],
queryFn: async () => {
- const res = await fetch("/api/connectors/ibm_cos/defaults");
- return res.json();
+ const res = await apiClient.get("/connectors/ibm_cos/defaults");
+ return res.data;
},
staleTime: 0,
});
diff --git a/frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketStatusQuery.ts b/frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketStatusQuery.ts
index 2a4b81b89..653d063db 100644
--- a/frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketStatusQuery.ts
+++ b/frontend/enhancements/connectors/ibm-cos/useIBMCOSBucketStatusQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface IBMCOSBucketStatus {
name: string;
@@ -9,15 +10,14 @@ export interface IBMCOSBucketStatus {
async function fetchIBMCOSBucketStatus(
connectionId: string,
): Promise<IBMCOSBucketStatus[]> {
- const res = await fetch(
- `/api/connectors/ibm_cos/${connectionId}/bucket-status`,
+ const res = await apiClient.get<{ buckets: IBMCOSBucketStatus[] }>(
+ `/connectors/ibm_cos/${connectionId}/bucket-status`,
);
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
+ if (res.status < 200 || res.status >= 300) {
+ const err = (res.data ?? {}) as { error?: string };
throw new Error(err.error || "Failed to fetch bucket status");
}
- const data = await res.json();
- return data.buckets as IBMCOSBucketStatus[];
+ return res.data.buckets;
}
export function useIBMCOSBucketStatusQuery(
diff --git a/frontend/enhancements/connectors/ibm-cos/useIBMCOSConfigureMutation.ts b/frontend/enhancements/connectors/ibm-cos/useIBMCOSConfigureMutation.ts
index 67e66c97a..e83daa978 100644
--- a/frontend/enhancements/connectors/ibm-cos/useIBMCOSConfigureMutation.ts
+++ b/frontend/enhancements/connectors/ibm-cos/useIBMCOSConfigureMutation.ts
@@ -1,4 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface IBMCOSConfigurePayload {
auth_mode: "iam" | "hmac";
@@ -17,13 +18,10 @@ export interface IBMCOSConfigurePayload {
}
async function configureIBMCOS(payload: IBMCOSConfigurePayload) {
- const res = await fetch("/api/connectors/ibm_cos/configure", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(payload),
- });
- const data = await res.json();
- if (!res.ok) throw new Error(data.error || "Failed to configure IBM COS");
+ const res = await apiClient.post("/connectors/ibm_cos/configure", payload);
+ const data = res.data ?? {};
+ if (res.status < 200 || res.status >= 300)
+ throw new Error(data.error || "Failed to configure IBM COS");
return data as { connection_id: string; status: string };
}
diff --git a/frontend/enhancements/connectors/ibm-cos/useIBMCOSDefaultsQuery.ts b/frontend/enhancements/connectors/ibm-cos/useIBMCOSDefaultsQuery.ts
index 5e0edabd1..836e8309d 100644
--- a/frontend/enhancements/connectors/ibm-cos/useIBMCOSDefaultsQuery.ts
+++ b/frontend/enhancements/connectors/ibm-cos/useIBMCOSDefaultsQuery.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import { apiClient } from "@/lib/api-client";
export interface IBMCOSDefaults {
api_key_set: boolean;
@@ -13,9 +14,12 @@ export interface IBMCOSDefaults {
}
async function fetchIBMCOSDefaults(): Promise<IBMCOSDefaults> {
- const res = await fetch("/api/connectors/ibm_cos/defaults");
- if (!res.ok) throw new Error("Failed to fetch IBM COS defaults");
- return res.json();
+ const res = await apiClient.get<IBMCOSDefaults>(
+ "/connectors/ibm_cos/defaults",
+ );
+ if (res.status < 200 || res.status >= 300)
+ throw new Error("Failed to fetch IBM COS defaults");
+ return res.data;
}
export function useIBMCOSDefaultsQuery(options?: { enabled?: boolean }) {
diff --git a/frontend/lib/api-client.test.ts b/frontend/lib/api-client.test.ts
new file mode 100644
index 000000000..0cc90a589
--- /dev/null
+++ b/frontend/lib/api-client.test.ts
@@ -0,0 +1,98 @@
+import { HttpResponse, http } from "msw";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { server } from "@/test-utils/msw/server";
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.unstubAllGlobals();
+ vi.resetModules();
+});
+
+describe("apiClient", () => {
+ it("sends requests through Axios below Next's basePath", async () => {
+ vi.stubEnv("NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ const seen = vi.fn();
+ server.use(
+ http.get("/openrag-fe/api/status", ({ request }) => {
+ seen(request.url);
+ return HttpResponse.json({ healthy: true });
+ }),
+ );
+
+ const { apiClient } = await import("./api-client");
+ const response = await apiClient.get("/status");
+
+ expect(response.status).toBe(200);
+ expect(response.data).toEqual({ healthy: true });
+ expect(seen).toHaveBeenCalledWith(
+ "http://localhost:3000/openrag-fe/api/status",
+ );
+ });
+
+ it("does not treat a non-2xx response as a transport failure", async () => {
+ vi.stubEnv("NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ server.use(
+ http.get("/openrag-fe/api/forbidden", () =>
+ HttpResponse.json({ error: "forbidden" }, { status: 403 }),
+ ),
+ );
+ const { apiClient } = await import("./api-client");
+ const response = await apiClient.get("/forbidden");
+
+ expect(response.status).toBe(403);
+ expect(response.data).toEqual({ error: "forbidden" });
+ });
+
+ it("does not redirect for a 401 without a login URL", async () => {
+ const location = {
+ origin: "http://localhost:3000",
+ href: "http://localhost:3000/current-page",
+ };
+ vi.stubGlobal("window", { location });
+ server.use(
+ http.get("/api/unauthorized", () =>
+ HttpResponse.json(
+ { error: "invalid provider credentials" },
+ { status: 401 },
+ ),
+ ),
+ );
+ const { apiClient } = await import("./api-client");
+ const response = await apiClient.get("/unauthorized");
+
+ expect(response.status).toBe(401);
+ expect(location.href).toBe("http://localhost:3000/current-page");
+ });
+
+ it("does not use the API base URL for absolute third-party URLs", async () => {
+ const { apiClient } = await import("./api-client");
+ expect(
+ apiClient.getUri({ url: "https://graph.microsoft.com/v1.0/me" }),
+ ).toBe("https://graph.microsoft.com/v1.0/me");
+ });
+
+ it("falls back to the base-path login page for unsafe redirects", async () => {
+ vi.stubEnv("NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ const { getUnauthorizedRedirectUrl } = await import("./api-client");
+
+ expect(getUnauthorizedRedirectUrl("https://evil.example/login")).toBe(
+ "/openrag-fe/login",
+ );
+ expect(getUnauthorizedRedirectUrl("//evil.example/login")).toBe(
+ "/openrag-fe/login",
+ );
+ expect(getUnauthorizedRedirectUrl("http://[invalid/login")).toBe(
+ "/openrag-fe/login",
+ );
+ expect(getUnauthorizedRedirectUrl("/auth/callback")).toBe(
+ "/openrag-fe/auth/callback",
+ );
+ });
+
+ it("rejects backslash-based cross-origin redirects without a base path", async () => {
+ vi.stubEnv("NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH", "");
+ const { getUnauthorizedRedirectUrl } = await import("./api-client");
+
+ expect(getUnauthorizedRedirectUrl("/\\evil.example/login")).toBe("/login");
+ });
+});
diff --git a/frontend/lib/api-client.ts b/frontend/lib/api-client.ts
new file mode 100644
index 000000000..c43c3aa90
--- /dev/null
+++ b/frontend/lib/api-client.ts
@@ -0,0 +1,69 @@
+import axios, { type AxiosResponse } from "axios";
+import {
+ frontendApiBasePath,
+ withFrontendBasePath,
+} from "./frontend-base-path";
+
+const runtimeApiBasePath =
+ typeof window === "undefined"
+ ? frontendApiBasePath
+ : new URL(frontendApiBasePath, window.location.origin).toString();
+
+/**
+ * Same-origin client for browser calls to Next's catch-all API proxy.
+ *
+ * The base URL includes Next's build-time basePath, so `apiClient.get("/tasks")`
+ * reaches `/openrag-fe/api/tasks` when the app is mounted at `/openrag-fe`.
+ */
+export const apiClient = axios.create({
+ baseURL: runtimeApiBasePath,
+ withCredentials: true,
+ // Existing callers have several legitimate non-2xx status branches. Keep
+ // those explicit rather than turning them into Axios rejections.
+ validateStatus: () => true,
+});
+
+export function getUnauthorizedRedirectUrl(redirectUrl: unknown): string {
+ const fallback = withFrontendBasePath("/login");
+ if (typeof redirectUrl !== "string") return fallback;
+
+ try {
+ if (typeof window === "undefined") return fallback;
+ const url = new URL(redirectUrl, window.location.origin);
+ if (url.origin !== window.location.origin) return fallback;
+
+ url.pathname = withFrontendBasePath(url.pathname);
+ // Keep relative application paths relative, while preserving absolute
+ // same-origin candidates returned by the backend.
+ if (redirectUrl.startsWith("/") && !redirectUrl.startsWith("//")) {
+ return `${url.pathname}${url.search}${url.hash}`;
+ }
+ return url.toString();
+ } catch {
+ // Malformed redirect URLs fall back to the local login page.
+ }
+
+ // Cross-origin redirect URLs are rejected to prevent open redirects, but a
+ // local login fallback still gives the user a way to recover from a 401.
+ return fallback;
+}
+
+function redirectForUnauthorized(response: AxiosResponse<unknown>) {
+ if (typeof window === "undefined" || response.status !== 401) return;
+
+ const payload = response.data;
+ if (!payload || typeof payload !== "object") return;
+
+ const redirectUrl =
+ (payload as Record<string, unknown>).redirect_url ||
+ (payload as Record<string, unknown>).redirectUrl ||
+ (payload as Record<string, unknown>).redirect;
+ if (typeof redirectUrl !== "string" || !redirectUrl) return;
+
+ window.location.href = getUnauthorizedRedirectUrl(redirectUrl);
+}
+
+apiClient.interceptors.response.use((response) => {
+ redirectForUnauthorized(response);
+ return response;
+});
diff --git a/frontend/lib/fetch-server.ts b/frontend/lib/fetch-server.ts
deleted file mode 100644
index 80cfa3e7b..000000000
--- a/frontend/lib/fetch-server.ts
+++ /dev/null
@@ -1,47 +0,0 @@
-import { cookies, headers } from "next/headers";
-
-export async function fetchFromBackend(
- path: string,
- init?: RequestInit,
-): Promise<Response> {
- const backendHost = process.env.OPENRAG_BACKEND_HOST || "localhost";
- const backendSSL = process.env.OPENRAG_BACKEND_SSL === "true";
- const backendPort = process.env.OPENRAG_BACKEND_PORT || "8000";
- const baseUrl = backendSSL
- ? `https://${backendHost}:${backendPort}`
- : `http://${backendHost}:${backendPort}`;
-
- const cookieStore = await cookies();
- const incoming = await headers();
-
- // Forward the gateway-injected auth headers, not just the cookie. In RBAC
- // mode (OPENRAG_RBAC_ENFORCE=true) the backend derives identity/permissions
- // from the JWT in the Authorization header and ignores the session cookie
- // (src/dependencies.py). The browser proxy (app/api/[...path]/route.ts)
- // already forwards these; server components must too, or server-rendered
- // permission checks (e.g. settings/[tab]/page.tsx) see no permissions and
- // wrongly redirect. Header names honor the backend's env overrides.
- const jwtAuthHeader = (
- process.env.OPENRAG_JWT_AUTH_HEADER || "Authorization"
- ).toLowerCase();
- const ibmCredentialsHeader = (
- process.env.IBM_CREDENTIALS_HEADER || "X-IBM-LH-Credentials"
- ).toLowerCase();
-
- const forwarded: Record<string, string> = {
- Cookie: cookieStore.toString(),
- };
- const authValue = incoming.get(jwtAuthHeader);
- if (authValue) forwarded[jwtAuthHeader] = authValue;
- const credentialsValue = incoming.get(ibmCredentialsHeader);
- if (credentialsValue) forwarded[ibmCredentialsHeader] = credentialsValue;
-
- return fetch(`${baseUrl}/${path}`, {
- ...init,
- headers: {
- ...forwarded,
- ...init?.headers,
- },
- cache: "no-store",
- });
-}
diff --git a/frontend/lib/frontend-base-path.test.ts b/frontend/lib/frontend-base-path.test.ts
new file mode 100644
index 000000000..eaa7b6bed
--- /dev/null
+++ b/frontend/lib/frontend-base-path.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { normalizeFrontendBasePath } from "./frontend-base-path";
+
+describe("normalizeFrontendBasePath", () => {
+ it.each([
+ [undefined, ""],
+ ["", ""],
+ ["/", ""],
+ ["openrag-fe", "/openrag-fe"],
+ [" /openrag-fe/ ", "/openrag-fe"],
+ ["/platform/openrag-fe///", "/platform/openrag-fe"],
+ ])("normalizes %j to %j", (value, expected) => {
+ expect(normalizeFrontendBasePath(value)).toBe(expected);
+ });
+
+ it.each([
+ "https://example.com/openrag-fe",
+ "/openrag-fe?tab=1",
+ "/x#y",
+ ])("rejects a URL rather than a path (%s)", (value) => {
+ expect(() => normalizeFrontendBasePath(value)).toThrow(
+ "OPENRAG_FRONTEND_BASE_PATH",
+ );
+ });
+});
diff --git a/frontend/lib/frontend-base-path.ts b/frontend/lib/frontend-base-path.ts
new file mode 100644
index 000000000..600bfb533
--- /dev/null
+++ b/frontend/lib/frontend-base-path.ts
@@ -0,0 +1,60 @@
+/**
+ * Return the path prefix under which Next serves the frontend.
+ *
+ * Next requires `basePath` values to be known at build time. Keep the
+ * normalization shared between next.config.ts and browser API requests so a
+ * deployment cannot put pages under one prefix and API calls under another.
+ */
+export function normalizeFrontendBasePath(value?: string): string {
+ const trimmed = value?.trim();
+ if (!trimmed || trimmed === "/") return "";
+
+ const prefixed = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+ const normalized = prefixed.replace(/\/+$/, "");
+
+ if (
+ !normalized ||
+ normalized.includes("?") ||
+ normalized.includes("#") ||
+ normalized.includes("://")
+ ) {
+ throw new Error(
+ "OPENRAG_FRONTEND_BASE_PATH must be a path such as /openrag-fe",
+ );
+ }
+
+ return normalized;
+}
+
+export const frontendBasePath = normalizeFrontendBasePath(
+ process.env.NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH,
+);
+
+export const frontendApiBasePath = `${frontendBasePath}/api`;
+
+/** Prefix an application-local path without changing external URLs. */
+export function withFrontendBasePath(path: string): string {
+ if (!frontendBasePath || !path.startsWith("/")) return path;
+ if (path === frontendBasePath || path.startsWith(`${frontendBasePath}/`)) {
+ return path;
+ }
+ return `${frontendBasePath}${path}`;
+}
+
+/** Remove Next's basePath before passing an existing browser path to its router. */
+export function withoutFrontendBasePath(path: string): string {
+ if (!frontendBasePath || !path.startsWith(frontendBasePath)) return path;
+ if (path === frontendBasePath) return "/";
+ if (path.startsWith(`${frontendBasePath}/`)) {
+ return path.slice(frontendBasePath.length);
+ }
+ return path;
+}
+
+/** Build an absolute same-origin URL for OAuth callbacks and redirects. */
+export function frontendUrl(
+ path: string,
+ origin = window.location.origin,
+): string {
+ return new URL(withFrontendBasePath(path), origin).toString();
+}
diff --git a/frontend/lib/upload-utils.ts b/frontend/lib/upload-utils.ts
index e97920ad1..c01df2d28 100644
--- a/frontend/lib/upload-utils.ts
+++ b/frontend/lib/upload-utils.ts
@@ -1,3 +1,17 @@
+import { apiClient } from "@/lib/api-client";
+
+function getUploadErrorMessage(data: unknown): string {
+ if (typeof data === "string") return data;
+ if (!data || typeof data !== "object") return "";
+
+ const payload = data as Record<string, unknown>;
+ for (const key of ["error", "detail", "message"]) {
+ if (typeof payload[key] === "string" && payload[key]) {
+ return payload[key];
+ }
+ }
+ return "";
+}
export type UploadContextResult =
| { type: "task"; taskId: string }
| { type: "direct"; filename: string; responseId: string };
@@ -14,17 +28,14 @@ export async function uploadFileForContext(
formData.append("previous_response_id", previousResponseId);
}
- const response = await fetch("/api/upload_context", {
- method: "POST",
- body: formData,
- });
+ const response = await apiClient.post("/upload_context", formData);
- if (!response.ok) {
- const errorText = await response.text();
+ if (response.status < 200 || response.status >= 300) {
+ const errorText = getUploadErrorMessage(response.data);
throw new Error(errorText || "Failed to process document");
}
- const result = await response.json();
+ const result = response.data;
if (response.status === 201) {
const taskId = result.task_id || result.id;
@@ -67,18 +78,18 @@ export interface UploadFileResult {
export async function duplicateCheck(
file: File,
): Promise<DuplicateCheckResponse> {
- const response = await fetch(
- `/api/documents/check-filename?filename=${encodeURIComponent(file.name)}`,
+ const response = await apiClient.get(
+ `/documents/check-filename?filename=${encodeURIComponent(file.name)}`,
);
- if (!response.ok) {
- const errorText = await response.text();
+ if (response.status < 200 || response.status >= 300) {
+ const errorText = getUploadErrorMessage(response.data);
throw new Error(
errorText || `Failed to check duplicates: ${response.statusText}`,
);
}
- return response.json();
+ return response.data;
}
export async function uploadFiles(
@@ -95,22 +106,26 @@ export async function uploadFiles(
formData.append("preview", "true");
}
- const uploadResponse = await fetch("/api/router/upload_ingest", {
- method: "POST",
- body: formData,
- });
+ const uploadResponse = await apiClient.post(
+ "/router/upload_ingest",
+ formData,
+ );
let payload: unknown;
try {
- payload = await uploadResponse.json();
+ payload = uploadResponse.data;
} catch {
throw new Error("Upload failed: unable to parse server response");
}
+ if (typeof payload === "string") {
+ throw new Error("Upload failed: unable to parse server response");
+ }
+
const json = typeof payload === "object" && payload !== null ? payload : {};
- if (!uploadResponse.ok) {
- const errorMessage = (json as { error?: string }).error || "Upload failed";
+ if (uploadResponse.status < 200 || uploadResponse.status >= 300) {
+ const errorMessage = getUploadErrorMessage(json) || "Upload failed";
throw new Error(errorMessage);
}
@@ -151,25 +166,28 @@ export async function uploadFile(
formData.append("preview", "true");
}
- const uploadResponse = await fetch("/api/router/upload_ingest", {
- method: "POST",
- body: formData,
- });
+ const uploadResponse = await apiClient.post(
+ "/router/upload_ingest",
+ formData,
+ );
let payload: unknown;
try {
- payload = await uploadResponse.json();
+ payload = uploadResponse.data;
} catch (_error) {
throw new Error("Upload failed: unable to parse server response");
}
+ if (typeof payload === "string") {
+ throw new Error("Upload failed: unable to parse server response");
+ }
+
const uploadIngestJson =
typeof payload === "object" && payload !== null ? payload : {};
- if (!uploadResponse.ok) {
+ if (uploadResponse.status < 200 || uploadResponse.status >= 300) {
const errorMessage =
- (uploadIngestJson as { error?: string }).error ||
- "Upload and ingest failed";
+ getUploadErrorMessage(uploadIngestJson) || "Upload and ingest failed";
throw new Error(errorMessage);
}
diff --git a/frontend/next.config.ts b/frontend/next.config.ts
index 6582603f7..06ada539b 100644
--- a/frontend/next.config.ts
+++ b/frontend/next.config.ts
@@ -2,6 +2,31 @@ import dotenv from "dotenv";
import type { NextConfig } from "next";
import path from "path";
+// Keep this config self-contained: next start evaluates next.config.ts from
+// the production image, where application source files under lib/ are not
+// copied. The browser-side client has the same normalization in
+// lib/frontend-base-path.ts.
+function normalizeFrontendBasePath(value?: string): string {
+ const trimmed = value?.trim();
+ if (!trimmed || trimmed === "/") return "";
+
+ const prefixed = trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
+ const normalized = prefixed.replace(/\/+$/, "");
+
+ if (
+ !normalized ||
+ normalized.includes("?") ||
+ normalized.includes("#") ||
+ normalized.includes("://")
+ ) {
+ throw new Error(
+ "OPENRAG_FRONTEND_BASE_PATH must be a path such as /openrag-fe",
+ );
+ }
+
+ return normalized;
+}
+
// Load environment variables from the root env file. Honors ENV_FILE (set by
// the Makefile) so per-instance env files like `.env.instance2` are respected;
// defaults to `.env`. Absolute ENV_FILE paths are used as-is.
@@ -9,6 +34,10 @@ dotenv.config({
path: path.resolve(process.cwd(), "..", process.env.ENV_FILE || ".env"),
});
+const frontendBasePath = normalizeFrontendBasePath(
+ process.env.OPENRAG_FRONTEND_BASE_PATH,
+);
+
function getAllowedDevOrigins(): string[] {
const allowedDevOrigins = process.env.NEXT_ALLOWED_DEV_ORIGINS;
@@ -26,6 +55,12 @@ function getAllowedDevOrigins(): string[] {
}
const nextConfig: NextConfig = {
+ // `basePath` is compiled into the browser bundle. The same value is exposed
+ // below so the Axios API client calls /<basePath>/api rather than /api.
+ basePath: frontendBasePath,
+ env: {
+ NEXT_PUBLIC_OPENRAG_FRONTEND_BASE_PATH: frontendBasePath,
+ },
// Build/dev output directory. Overridable via NEXT_DIST_DIR so multiple
// `next dev` servers can run simultaneously from this same directory: Next.js
// 16 acquires a lock at `<distDir>/lock` keyed on the project dir + distDir
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 8800eb3cf..f66bee2b6 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -30,6 +30,7 @@
"@tanstack/react-query": "^5.101.2",
"ag-grid-community": "^36.0.0",
"ag-grid-react": "^36.0.0",
+ "axios": "^1.20.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
@@ -292,9 +293,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -312,9 +310,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -332,9 +327,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -352,9 +344,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT OR Apache-2.0",
"optional": true,
"os": [
@@ -938,9 +927,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -957,9 +943,6 @@
"cpu": [
"arm64"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -976,9 +959,6 @@
"cpu": [
"x64"
],
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -995,9 +975,6 @@
"cpu": [
"x64"
],
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1236,9 +1213,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1256,9 +1230,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1276,9 +1247,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1296,9 +1264,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1316,9 +1281,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1336,9 +1298,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1356,9 +1315,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1376,9 +1332,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1591,9 +1544,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1608,9 +1558,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1625,9 +1572,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1642,9 +1586,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1659,9 +1600,6 @@
"riscv64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1676,9 +1614,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1693,9 +1628,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -1710,9 +1642,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -3906,6 +3835,18 @@
"integrity": "sha512-ciXqjZygVLk3tnZWOAQyOxP48Ju2ZmaSAtIebekXJwHqA7vB+NJ8ZME/O4XTRpInTSHn2KSu/KTxgWJO8dduiw==",
"license": "MIT"
},
+ "node_modules/agent-base": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
+ "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 6.0.0"
+ }
+ },
"node_modules/ansi-escapes": {
"version": "7.3.0",
"resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz",
@@ -4030,6 +3971,12 @@
"integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
"license": "MIT"
},
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "license": "MIT"
+ },
"node_modules/attr-accept": {
"version": "2.2.5",
"resolved": "https://registry.npmjs.org/attr-accept/-/attr-accept-2.2.5.tgz",
@@ -4075,6 +4022,18 @@
"postcss": "^8.1.0"
}
},
+ "node_modules/axios": {
+ "version": "1.20.0",
+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz",
+ "integrity": "sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==",
+ "license": "MIT",
+ "dependencies": {
+ "follow-redirects": "^1.16.0",
+ "form-data": "^4.0.6",
+ "https-proxy-agent": "^5.0.1",
+ "proxy-from-env": "^2.1.0"
+ }
+ },
"node_modules/bail": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/bail/-/bail-2.0.2.tgz",
@@ -4172,6 +4131,19 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/camelcase-css": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -4523,6 +4495,18 @@
"node": ">=18"
}
},
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/comma-separated-tokens": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
@@ -4701,6 +4685,15 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/dequal": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz",
@@ -4778,6 +4771,20 @@
"node": ">=4"
}
},
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/electron-to-chromium": {
"version": "1.5.430",
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.430.tgz",
@@ -4822,6 +4829,15 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
@@ -4838,6 +4854,33 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/es-object-atoms": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -5026,6 +5069,42 @@
"integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==",
"license": "MIT"
},
+ "node_modules/follow-redirects": {
+ "version": "1.16.1",
+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.1.tgz",
+ "integrity": "sha512-FNvFGzoMLWmE6Yj9spb/zjd7yiNCHiAW9/Tg9CXrQ8wuu32HtlJOwWO11OJafl5FfY3DxTdQ0vj42zU1kvv5jg==",
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/RubenVerborgh"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ },
+ "peerDependenciesMeta": {
+ "debug": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/form-data": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.4",
+ "mime-types": "^2.1.35"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/format": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz",
@@ -5150,6 +5229,30 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/get-nonce": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz",
@@ -5159,6 +5262,19 @@
"node": ">=6"
}
},
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/get-tsconfig": {
"version": "4.14.0",
"resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.14.0.tgz",
@@ -5184,6 +5300,18 @@
"node": ">= 6"
}
},
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/graphql": {
"version": "16.14.2",
"resolved": "https://registry.npmjs.org/graphql/-/graphql-16.14.2.tgz",
@@ -5204,6 +5332,33 @@
"node": ">=8"
}
},
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-tostringtag": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
+ "license": "MIT",
+ "dependencies": {
+ "has-symbols": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/hasown": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
@@ -5465,6 +5620,19 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/https-proxy-agent": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
+ "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "6",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/husky": {
"version": "9.1.7",
"resolved": "https://registry.npmjs.org/husky/-/husky-9.1.7.tgz",
@@ -6436,6 +6604,15 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/mathjax-full": {
"version": "3.2.2",
"resolved": "https://registry.npmjs.org/mathjax-full/-/mathjax-full-3.2.2.tgz",
@@ -7300,6 +7477,27 @@
"node": ">=8.6"
}
},
+ "node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/mimic-function": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz",
@@ -8082,6 +8280,15 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/proxy-from-env": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
+ "integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/punycode": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index e8cf88fba..6800b00c2 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -43,6 +43,7 @@
"@tanstack/react-query": "^5.101.2",
"ag-grid-community": "^36.0.0",
"ag-grid-react": "^36.0.0",
+ "axios": "^1.20.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
diff --git a/scripts/ci/run_integration_suite.sh b/scripts/ci/run_integration_suite.sh
index d62d616e1..40b6cd00f 100755
--- a/scripts/ci/run_integration_suite.sh
+++ b/scripts/ci/run_integration_suite.sh
@@ -15,6 +15,16 @@ fi
COMPOSE_PROJECT_NAME=""
OPENSEARCH_PORT=""
LANGFLOW_PORT=""
+if [[ ${OPENRAG_FRONTEND_BASE_PATH+x} != x ]]; then
+ OPENRAG_FRONTEND_BASE_PATH=""
+ if [[ -f "$env_file" ]]; then
+ OPENRAG_FRONTEND_BASE_PATH="$(
+ { grep -E '^OPENRAG_FRONTEND_BASE_PATH=' "$env_file" || [[ $? -eq 1 ]]; } |
+ cut -d= -f2- |
+ tr -d '"'\'
+ )"
+ fi
+fi
if [[ -f "$env_file" ]]; then
COMPOSE_PROJECT_NAME="$(grep -E '^COMPOSE_PROJECT_NAME=' "$env_file" | cut -d= -f2- | tr -d '"'\')"
OPENSEARCH_PORT="$(grep -E '^OPENSEARCH_PORT=' "$env_file" | cut -d= -f2- | tr -d '"'\')"
@@ -24,6 +34,14 @@ fi
COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-openrag}"
OPENSEARCH_PORT="${OPENSEARCH_PORT:-9200}"
LANGFLOW_PORT="${LANGFLOW_PORT:-7860}"
+export OPENRAG_FRONTEND_BASE_PATH
+frontend_base_path="${OPENRAG_FRONTEND_BASE_PATH#/}"
+frontend_base_path="${frontend_base_path%/}"
+if [[ -n "$frontend_base_path" ]]; then
+ FRONTEND_URL="http://localhost:3000/${frontend_base_path}"
+else
+ FRONTEND_URL="http://localhost:3000"
+fi
compose_cmd+=("-p" "$COMPOSE_PROJECT_NAME")
@@ -288,7 +306,7 @@ run_attempt() {
test_jwt_opensearch || exit_code=1
;;
sdk-python)
- if ! wait_for_url "frontend at http://localhost:3000" "http://localhost:3000/" 60; then
+ if ! wait_for_url "frontend at ${FRONTEND_URL}" "${FRONTEND_URL}/" 60; then
return 1
fi
echo "::group::SDK Integration Tests (Python)"
@@ -299,11 +317,11 @@ run_attempt() {
echo "${red}ERROR: uv pip install failed${nc}"
return 1
fi
- SDK_TESTS_ONLY=true OPENRAG_URL=http://localhost:3000 uv run pytest tests/integration/sdk/ -vv -s --log-file=service-logs/pytest-sdk.log --log-file-level=DEBUG --junitxml=service-logs/junit-sdk-python.xml || exit_code=1
+ SDK_TESTS_ONLY=true OPENRAG_URL="${FRONTEND_URL}" uv run pytest tests/integration/sdk/ -vv -s --log-file=service-logs/pytest-sdk.log --log-file-level=DEBUG --junitxml=service-logs/junit-sdk-python.xml || exit_code=1
echo "::endgroup::"
;;
sdk-typescript)
- if ! wait_for_url "frontend at http://localhost:3000" "http://localhost:3000/" 60; then
+ if ! wait_for_url "frontend at ${FRONTEND_URL}" "${FRONTEND_URL}/" 60; then
return 1
fi
echo "::group::SDK Integration Tests (TypeScript)"
@@ -311,7 +329,7 @@ run_attempt() {
echo "${purple} SDK Integration Tests (TypeScript)${nc}"
echo "${cyan}════════════════════════════════════════${nc}"
cd sdks/typescript
- npm install && npm run build && OPENRAG_URL=http://localhost:3000 npm test -- --reporter=junit --outputFile=../../service-logs/junit-sdk-typescript.xml || exit_code=1
+ npm install && npm run build && OPENRAG_URL="${FRONTEND_URL}" npm test -- --reporter=junit --outputFile=../../service-logs/junit-sdk-typescript.xml || exit_code=1
cd ../..
echo "::endgroup::"
;;