Skip to content

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

Python

feat: Implemented runtime basepath config (#2505) (#2561)

Lucas Oliveira83216b014191
diff --git a/.env.example b/.env.example
index 36c4aafd5..75610c747 100644
--- a/.env.example
+++ b/.env.example
@@ -70,8 +70,8 @@ NUDGES_FLOW_ID=ebc01d31-1976-46ce-a385-b0240327226c
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.
+# sub-path (for example https://example.com/openrag-fe). The frontend container
+# applies this value at startup, so changing it does not require an image rebuild.
# OPENRAG_FRONTEND_BASE_PATH=/openrag-fe
# URL Docker-hosted services use to call the backend in host-backend mode.
diff --git a/Dockerfile.frontend b/Dockerfile.frontend
index 36b022224..7cdf58dad 100644
--- a/Dockerfile.frontend
+++ b/Dockerfile.frontend
@@ -26,10 +26,9 @@ 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}
+# Restrict the placeholder to container image builds. The entrypoint replaces
+# it in a writable per-pod copy of the assets before starting the server.
+ENV OPENRAG_FRONTEND_RUNTIME_BASE_PATH=true
COPY --from=deps /opt/app-root/src/node_modules ./node_modules
COPY --from=deps /opt/app-root/src/stubs ./stubs
@@ -47,12 +46,6 @@ 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
-
-
# The npm CLI is only needed to install and build, so the runtime stage drops
# it. Its bundled dependencies (e.g. undici via node-gyp) otherwise ship in the
# image and get flagged by scanners (CVE-2026-15157, CVE-2026-16728,
@@ -62,8 +55,7 @@ RUN microdnf update -y \
&& microdnf clean all && rm -rf /var/cache/yum
ENV NODE_ENV=production \
- NEXT_TELEMETRY_DISABLED=1 \
- OPENRAG_FRONTEND_BASE_PATH=${OPENRAG_FRONTEND_BASE_PATH}
+ NEXT_TELEMETRY_DISABLED=1
# 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.
@@ -71,18 +63,13 @@ ENV NODE_ENV=production \
# to the front.
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/app-root/bin:/opt/app-root/src/bin:/opt/app-root/src/.local/bin
-COPY --from=builder --chown=1001:0 /opt/app-root/src/package*.json ./
-COPY --from=builder --chown=1001:0 /opt/app-root/src/stubs ./stubs
-COPY --from=builder --chown=1001:0 /opt/app-root/src/.next ./.next
+COPY --from=builder --chown=1001:0 /opt/app-root/src/.next/standalone ./
+COPY --from=builder --chown=1001:0 /opt/app-root/src/.next/static ./.next/static
COPY --from=builder --chown=1001:0 /opt/app-root/src/public ./public
-COPY --from=builder --chown=1001:0 /opt/app-root/src/node_modules ./node_modules
-COPY --from=builder --chown=1001:0 /opt/app-root/src/next.config.* ./
-COPY --from=builder --chown=1001:0 /opt/app-root/src/postcss.config.* ./
-COPY --from=builder --chown=1001:0 /opt/app-root/src/tailwind.config.* ./
-COPY --from=builder --chown=1001:0 /opt/app-root/src/biome.json* ./
+COPY --chown=1001:0 frontend/entrypoint.sh ./entrypoint.sh
EXPOSE 3000 9090
USER 1001
-# Run Next.js directly with node: npm is not installed in this stage.
-CMD ["node", "node_modules/next/dist/bin/next", "start"]
+ENTRYPOINT ["./entrypoint.sh"]
+CMD ["node", "server.js"]
diff --git a/Makefile b/Makefile
index 955976f1f..a8457c212 100644
--- a/Makefile
+++ b/Makefile
@@ -24,13 +24,14 @@ 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.
+# Next.js compiles `basePath` into the frontend bundle. Production images carry
+# a placeholder that their entrypoint replaces at startup; the normalized path
+# is still used for local health checks and URLs.
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)
+FRONTEND_PORT ?= 3000
+FRONTEND_LOCAL_URL := http://localhost:$(FRONTEND_PORT)$(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.
@@ -528,7 +529,7 @@ dev: ensure-langflow-data ensure-backend-volumes check-env ## Start full stack w
$(COMPOSE_CMD) -f docker-compose.yml -f docker-compose.gpu.yml up -d
@echo "$(PURPLE)Services started!$(NC)"
@echo " $(CYAN)Backend:$(NC) http://openrag-backend"
- @echo " $(CYAN)Frontend:$(NC) http://localhost:$${FRONTEND_PORT:-3000}"
+ @echo " $(CYAN)Frontend:$(NC) $(FRONTEND_LOCAL_URL)"
@echo " $(CYAN)Langflow:$(NC) http://localhost:$${LANGFLOW_PORT:-7860}"
@echo " $(CYAN)OpenSearch:$(NC) http://localhost:$${OPENSEARCH_PORT:-9200}"
@echo " $(CYAN)Dashboards:$(NC) http://localhost:$${OPENSEARCH_DASHBOARDS_PORT:-5601}"
@@ -538,7 +539,7 @@ dev-cpu: ensure-langflow-data ensure-backend-volumes check-env ## Start full sta
$(COMPOSE_CMD) up -d $(SERVICES)
@echo "$(PURPLE)Services started!$(NC)"
@echo " $(CYAN)Backend:$(NC) http://openrag-backend"
- @echo " $(CYAN)Frontend:$(NC) http://localhost:$${FRONTEND_PORT:-3000}"
+ @echo " $(CYAN)Frontend:$(NC) $(FRONTEND_LOCAL_URL)"
@echo " $(CYAN)Langflow:$(NC) http://localhost:$${LANGFLOW_PORT:-7860}"
@echo " $(CYAN)OpenSearch:$(NC) http://localhost:$${OPENSEARCH_PORT:-9200}"
@echo " $(CYAN)Dashboards:$(NC) http://localhost:$${OPENSEARCH_DASHBOARDS_PORT:-5601}"
@@ -550,7 +551,7 @@ dev-build: ensure-langflow-data ensure-backend-volumes check-env ## Start full s
$(COMPOSE_CMD) -f docker-compose.yml -f docker-compose.gpu.yml up -d
@echo "$(PURPLE)Services started!$(NC)"
@echo " $(CYAN)Backend:$(NC) http://openrag-backend"
- @echo " $(CYAN)Frontend:$(NC) http://localhost:$${FRONTEND_PORT:-3000}"
+ @echo " $(CYAN)Frontend:$(NC) $(FRONTEND_LOCAL_URL)"
@echo " $(CYAN)Langflow:$(NC) http://localhost:$${LANGFLOW_PORT:-7860}"
@echo " $(CYAN)OpenSearch:$(NC) http://localhost:$${OPENSEARCH_PORT:-9200}"
@echo " $(CYAN)Dashboards:$(NC) http://localhost:$${OPENSEARCH_DASHBOARDS_PORT:-5601}"
@@ -562,7 +563,7 @@ dev-build-cpu: ensure-langflow-data ensure-backend-volumes check-env ## Start fu
$(COMPOSE_CMD) up -d
@echo "$(PURPLE)Services started!$(NC)"
@echo " $(CYAN)Backend:$(NC) http://openrag-backend"
- @echo " $(CYAN)Frontend:$(NC) http://localhost:$${FRONTEND_PORT:-3000}"
+ @echo " $(CYAN)Frontend:$(NC) $(FRONTEND_LOCAL_URL)"
@echo " $(CYAN)Langflow:$(NC) http://localhost:$${LANGFLOW_PORT:-7860}"
@echo " $(CYAN)OpenSearch:$(NC) http://localhost:$${OPENSEARCH_PORT:-9200}"
@echo " $(CYAN)Dashboards:$(NC) http://localhost:$${OPENSEARCH_DASHBOARDS_PORT:-5601}"
@@ -864,7 +865,7 @@ backend: ## Run backend locally
uv run python src/main.py
frontend: ## Run frontend locally
- @echo "$(YELLOW)Starting frontend locally...$(NC)"
+ @echo "$(YELLOW)Starting frontend locally at $(FRONTEND_LOCAL_URL)...$(NC)"
@if [ ! -d "frontend/node_modules" ]; then echo "$(YELLOW)Installing frontend dependencies first...$(NC)"; cd frontend && npm install; fi
@ARCH=$$(uname -m); \
export ENV_FILE="$(abspath $(ENV_FILE))"; \
@@ -951,7 +952,7 @@ build-be: ## Build backend Docker image
build-fe: ## Build frontend Docker image
@echo "$(YELLOW)Building frontend image...$(NC)"
- $(CONTAINER_RUNTIME) build $(FRONTEND_BASE_PATH_BUILD_ARG) -t langflowai/openrag-frontend:latest -f Dockerfile.frontend .
+ $(CONTAINER_RUNTIME) build -t langflowai/openrag-frontend:latest -f Dockerfile.frontend .
@echo "$(PURPLE)Frontend image built.$(NC)"
build-lf: ## Build Langflow Docker image
@@ -1042,7 +1043,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 $(FRONTEND_BASE_PATH_BUILD_ARG) -t langflowai/openrag-frontend:$$IMAGE_TAG -f Dockerfile.frontend .; \
+ $(CONTAINER_RUNTIME) build -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)"
@@ -1200,7 +1201,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 $(FRONTEND_BASE_PATH_BUILD_ARG) -t langflowai/openrag-frontend:latest -f Dockerfile.frontend .; \
+ $(CONTAINER_RUNTIME) build -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"; \
diff --git a/docker-compose.yml b/docker-compose.yml
index e961faf49..568b92b56 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -210,13 +210,12 @@ 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
environment:
- OPENRAG_BACKEND_HOST=openrag-backend
+ - OPENRAG_FRONTEND_BASE_PATH=${OPENRAG_FRONTEND_BASE_PATH:-}
ports:
- "${FRONTEND_PORT:-3000}:3000"
diff --git a/docs/docs/reference/configuration.mdx b/docs/docs/reference/configuration.mdx
index 4d60344f9..fe475c507 100644
--- a/docs/docs/reference/configuration.mdx
+++ b/docs/docs/reference/configuration.mdx
@@ -368,7 +368,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_FRONTEND_BASE_PATH` | Not set | Optional URL prefix below which the complete frontend is served, such as `/openrag-fe`. Set it when starting the frontend container; the image applies it to a writable temporary copy of its assets, so no rebuild is required. Empty or `/` serves from the root. On Kubernetes, mount a writable volume at `/tmp` (the Helm chart does this by default). |
| `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. |
@@ -380,6 +380,8 @@ Configure general system components, session management, and logging.
| `SERVICE_NAME` | `openrag` | Service name used in log entries. |
| `SESSION_SECRET` | Automatically generated | Secret key for session management. If not provided, a secure random key is generated automatically. |
+The frontend base path accepts an optional leading slash and removes trailing slashes. It may contain only letters, digits, `/`, `.`, `_`, `~`, and `-`; double slashes and `.` or `..` segments are invalid. The container startup script updates a temporary copy of Next.js standalone output and browser assets, leaving the image files unchanged. Keep `/tmp` writable, or set `OPENRAG_FRONTEND_RUNTIME_DIR` to a writable directory outside the application source. Read-only root filesystems and custom runtime UIDs are supported when that runtime directory is writable.
+
## Observability and APM settings {#observability-and-apm-settings}
Instrument OpenRAG Backend with [IBM Instana](https://www.ibm.com/products/instana) for application performance monitoring and distributed tracing.
diff --git a/frontend/entrypoint.sh b/frontend/entrypoint.sh
new file mode 100755
index 000000000..50ada738b
--- /dev/null
+++ b/frontend/entrypoint.sh
@@ -0,0 +1,72 @@
+#!/bin/sh
+set -eu
+
+PLACEHOLDER="/NEXT_PUBLIC_BASE_PATH_PLACEHOLDER_a1b2c3d4"
+RUNTIME_DIR="${OPENRAG_FRONTEND_RUNTIME_DIR:-/tmp/openrag-frontend}"
+
+# OPENRAG_FRONTEND_BASE_PATH is the documented OpenRAG setting.
+TARGET_PATH="${OPENRAG_FRONTEND_BASE_PATH:-}"
+TARGET_PATH="$(printf '%s' "$TARGET_PATH" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
+
+if [ "$TARGET_PATH" = "/" ]; then
+ TARGET_PATH=""
+elif [ -n "$TARGET_PATH" ]; then
+ case "$TARGET_PATH" in
+ /*) ;;
+ *) TARGET_PATH="/$TARGET_PATH" ;;
+ esac
+ TARGET_PATH="$(printf '%s' "$TARGET_PATH" | sed 's:/*$::')"
+ if [ -z "$TARGET_PATH" ]; then
+ echo "OPENRAG_FRONTEND_BASE_PATH must be a path such as /openrag-fe" >&2
+ exit 1
+ fi
+
+ # The value is inserted into generated JavaScript and JSON. Restrict it to
+ # URL-path characters that are safe in each generated asset format.
+ case "$TARGET_PATH" in
+ *[!A-Za-z0-9/._~-]*|*'//'*|*'/./'*|*'/../'*|*'/.'|*'/..')
+ echo "OPENRAG_FRONTEND_BASE_PATH must be a path such as /openrag-fe" >&2
+ exit 1
+ ;;
+ esac
+fi
+
+if [ ! -d .next ] || [ ! -f server.js ]; then
+ echo "Frontend standalone output (.next and server.js) is required" >&2
+ exit 1
+fi
+
+echo "Replacing frontend base-path placeholder with: '${TARGET_PATH}'"
+
+# Next.js embeds basePath into server output and browser chunks. Do not mutate
+# the image layer: Kubernetes commonly makes it read-only. Copy the standalone
+# app to a pod-writable directory, patch that copy, and run it from there.
+# Do not preserve ownership: OpenShift can run the container as an arbitrary
+# non-root UID, which cannot restore the image files' original owner.
+if ! mkdir -p "$RUNTIME_DIR" || ! cp -R . "$RUNTIME_DIR"; then
+ echo "Unable to prepare frontend runtime assets in $RUNTIME_DIR." >&2
+ echo "Mount a writable volume at /tmp or set OPENRAG_FRONTEND_RUNTIME_DIR." >&2
+ exit 1
+fi
+export PLACEHOLDER TARGET_PATH
+replace_assets() {
+ find "$@" -type f -exec sh -c '
+ set -e
+ for file do
+ sed -i.bak "s|${PLACEHOLDER}|${TARGET_PATH}|g" "$file"
+ rm -f "$file.bak"
+ done
+ ' sh {} +
+}
+if [ -d "$RUNTIME_DIR/public" ]; then
+ if ! replace_assets "$RUNTIME_DIR/.next" "$RUNTIME_DIR/server.js" "$RUNTIME_DIR/public"; then
+ echo "Unable to apply OPENRAG_FRONTEND_BASE_PATH to runtime assets." >&2
+ exit 1
+ fi
+elif ! replace_assets "$RUNTIME_DIR/.next" "$RUNTIME_DIR/server.js"; then
+ echo "Unable to apply OPENRAG_FRONTEND_BASE_PATH to runtime assets." >&2
+ exit 1
+fi
+
+cd "$RUNTIME_DIR"
+exec "$@"
diff --git a/frontend/entrypoint.test.ts b/frontend/entrypoint.test.ts
new file mode 100644
index 000000000..6f4f19e58
--- /dev/null
+++ b/frontend/entrypoint.test.ts
@@ -0,0 +1,135 @@
+import { spawnSync } from "node:child_process";
+import {
+ mkdir,
+ mkdtemp,
+ readdir,
+ readFile,
+ rm,
+ writeFile,
+} from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const entrypoint = resolve(process.cwd(), "entrypoint.sh");
+const placeholder = "/NEXT_PUBLIC_BASE_PATH_PLACEHOLDER_a1b2c3d4";
+const fixtures: string[] = [];
+
+async function createStandaloneFixture() {
+ const directory = await mkdtemp(join(tmpdir(), "openrag-entrypoint-"));
+ fixtures.push(directory);
+ fixtures.push(`${directory}-runtime`);
+ await mkdir(join(directory, ".next/server/app"), { recursive: true });
+ await mkdir(join(directory, ".next/static/chunks"), { recursive: true });
+ await writeFile(
+ join(directory, "server.js"),
+ `console.log(JSON.stringify({basePath: "${placeholder}", api: "${placeholder}/api"}));\n`,
+ );
+ await writeFile(
+ join(directory, ".next/server/app/route.js"),
+ `server-route: ${placeholder}/api/status\n`,
+ );
+ await writeFile(
+ join(directory, ".next/static/chunks/app.js"),
+ `browser-route: ${placeholder}/api/status\n`,
+ );
+ return directory;
+}
+
+function start(directory: string, path?: string) {
+ const env = { ...process.env };
+ env.OPENRAG_FRONTEND_RUNTIME_DIR = `${directory}-runtime`;
+ if (path === undefined) {
+ delete env.OPENRAG_FRONTEND_BASE_PATH;
+ } else {
+ env.OPENRAG_FRONTEND_BASE_PATH = path;
+ }
+ return spawnSync("sh", [entrypoint, "node", "server.js"], {
+ cwd: directory,
+ env,
+ encoding: "utf8",
+ });
+}
+
+afterEach(async () => {
+ await Promise.all(
+ fixtures
+ .splice(0)
+ .map((directory) => rm(directory, { recursive: true, force: true })),
+ );
+});
+
+describe("frontend container entrypoint", () => {
+ it.each([
+ [undefined, ""],
+ ["", ""],
+ ["/", ""],
+ [" openrag-fe/ ", "/openrag-fe"],
+ ["/platform/openrag-fe///", "/platform/openrag-fe"],
+ ["/r-d_ui", "/r-d_ui"],
+ ])("starts the standalone server with %j mounted at %j", async (path, expected) => {
+ const directory = await createStandaloneFixture();
+ const result = start(directory, path);
+
+ expect(result.error).toBeUndefined();
+ expect(result.status, result.stderr).toBe(0);
+ expect(result.stdout).toContain(
+ JSON.stringify({ basePath: expected, api: `${expected}/api` }),
+ );
+ expect(
+ await readFile(
+ join(`${directory}-runtime`, ".next/server/app/route.js"),
+ "utf8",
+ ),
+ ).toBe(`server-route: ${expected}/api/status\n`);
+ expect(
+ await readFile(
+ join(`${directory}-runtime`, ".next/static/chunks/app.js"),
+ "utf8",
+ ),
+ ).toBe(`browser-route: ${expected}/api/status\n`);
+ expect(await readFile(join(directory, "server.js"), "utf8")).toContain(
+ placeholder,
+ );
+ expect(await readdir(`${directory}-runtime`)).not.toContain(
+ "server.js.bak",
+ );
+ expect(
+ await readdir(join(`${directory}-runtime`, ".next/static/chunks")),
+ ).not.toContain("app.js.bak");
+ });
+
+ it.each([
+ "https://example.com/app",
+ "/bad?query",
+ "/bad#fragment",
+ "//wrong-origin",
+ "////",
+ "/r&d|ui",
+ "/bad\\path",
+ "/a//b",
+ "/a/../b",
+ "/a/./b",
+ "/bad path",
+ "/bad\npath",
+ ])("rejects invalid path %j before touching output", async (path) => {
+ const directory = await createStandaloneFixture();
+ const result = start(directory, path);
+
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain("OPENRAG_FRONTEND_BASE_PATH");
+ expect(result.stdout).not.toContain("basePath");
+ expect(await readFile(join(directory, "server.js"), "utf8")).toContain(
+ placeholder,
+ );
+ });
+
+ it("fails clearly when standalone build output is missing", async () => {
+ const directory = await mkdtemp(join(tmpdir(), "openrag-entrypoint-"));
+ fixtures.push(directory);
+ const result = start(directory, "/openrag-fe");
+
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain("Frontend standalone output");
+ });
+});
diff --git a/frontend/lib/frontend-base-path.test.ts b/frontend/lib/frontend-base-path.test.ts
index eaa7b6bed..5cc6bd2d7 100644
--- a/frontend/lib/frontend-base-path.test.ts
+++ b/frontend/lib/frontend-base-path.test.ts
@@ -6,9 +6,11 @@ describe("normalizeFrontendBasePath", () => {
[undefined, ""],
["", ""],
["/", ""],
+ [" / ", ""],
["openrag-fe", "/openrag-fe"],
[" /openrag-fe/ ", "/openrag-fe"],
["/platform/openrag-fe///", "/platform/openrag-fe"],
+ ["/r-d_ui", "/r-d_ui"],
])("normalizes %j to %j", (value, expected) => {
expect(normalizeFrontendBasePath(value)).toBe(expected);
});
@@ -17,7 +19,15 @@ describe("normalizeFrontendBasePath", () => {
"https://example.com/openrag-fe",
"/openrag-fe?tab=1",
"/x#y",
- ])("rejects a URL rather than a path (%s)", (value) => {
+ "//wrong-origin",
+ "/r&d|ui",
+ "/bad\\path",
+ "/a//b",
+ "/a/../b",
+ "/a/./b",
+ "/bad path",
+ "/bad\npath",
+ ])("rejects an invalid 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
index 600bfb533..47a91a79f 100644
--- a/frontend/lib/frontend-base-path.ts
+++ b/frontend/lib/frontend-base-path.ts
@@ -14,9 +14,9 @@ export function normalizeFrontendBasePath(value?: string): string {
if (
!normalized ||
- normalized.includes("?") ||
- normalized.includes("#") ||
- normalized.includes("://")
+ !/^[A-Za-z0-9/._~-]+$/.test(normalized) ||
+ normalized.includes("//") ||
+ /\/\.{1,2}(\/|$)/.test(normalized)
) {
throw new Error(
"OPENRAG_FRONTEND_BASE_PATH must be a path such as /openrag-fe",
diff --git a/frontend/next.config.test.ts b/frontend/next.config.test.ts
new file mode 100644
index 000000000..3fd4b90ae
--- /dev/null
+++ b/frontend/next.config.test.ts
@@ -0,0 +1,59 @@
+import {
+ PHASE_DEVELOPMENT_SERVER,
+ PHASE_PRODUCTION_BUILD,
+} from "next/constants";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import createNextConfig from "./next.config";
+
+describe("next configuration base path", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it.each([
+ ["", ""],
+ ["/", ""],
+ [" openrag-fe/ ", "/openrag-fe"],
+ ])("normalizes production base path %j to %j", (path, expected) => {
+ vi.stubEnv("OPENRAG_FRONTEND_BASE_PATH", path);
+ vi.stubEnv("OPENRAG_FRONTEND_RUNTIME_BASE_PATH", "");
+
+ expect(createNextConfig(PHASE_PRODUCTION_BUILD).basePath).toBe(expected);
+ });
+
+ it("rejects paths that would route differently in the browser", () => {
+ vi.stubEnv("OPENRAG_FRONTEND_BASE_PATH", "/a/../b");
+ vi.stubEnv("OPENRAG_FRONTEND_RUNTIME_BASE_PATH", "");
+
+ expect(() => createNextConfig(PHASE_PRODUCTION_BUILD)).toThrow(
+ "OPENRAG_FRONTEND_BASE_PATH",
+ );
+ });
+
+ it("uses the configured path for a local production build", () => {
+ vi.stubEnv("OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ vi.stubEnv("OPENRAG_FRONTEND_RUNTIME_BASE_PATH", "");
+
+ expect(createNextConfig(PHASE_PRODUCTION_BUILD).basePath).toBe(
+ "/openrag-fe",
+ );
+ });
+
+ it("uses the placeholder only when building the container image", () => {
+ vi.stubEnv("OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ vi.stubEnv("OPENRAG_FRONTEND_RUNTIME_BASE_PATH", "true");
+
+ expect(createNextConfig(PHASE_PRODUCTION_BUILD).basePath).toBe(
+ "/NEXT_PUBLIC_BASE_PATH_PLACEHOLDER_a1b2c3d4",
+ );
+ });
+
+ it("keeps next dev configurable even when the image-build flag is set", () => {
+ vi.stubEnv("OPENRAG_FRONTEND_BASE_PATH", "/openrag-fe");
+ vi.stubEnv("OPENRAG_FRONTEND_RUNTIME_BASE_PATH", "true");
+
+ expect(createNextConfig(PHASE_DEVELOPMENT_SERVER).basePath).toBe(
+ "/openrag-fe",
+ );
+ });
+});
diff --git a/frontend/next.config.ts b/frontend/next.config.ts
index 06ada539b..d7c7604b6 100644
--- a/frontend/next.config.ts
+++ b/frontend/next.config.ts
@@ -1,5 +1,6 @@
import dotenv from "dotenv";
import type { NextConfig } from "next";
+import { PHASE_DEVELOPMENT_SERVER } from "next/constants";
import path from "path";
// Keep this config self-contained: next start evaluates next.config.ts from
@@ -15,9 +16,9 @@ function normalizeFrontendBasePath(value?: string): string {
if (
!normalized ||
- normalized.includes("?") ||
- normalized.includes("#") ||
- normalized.includes("://")
+ !/^[A-Za-z0-9/._~-]+$/.test(normalized) ||
+ normalized.includes("//") ||
+ /\/\.{1,2}(\/|$)/.test(normalized)
) {
throw new Error(
"OPENRAG_FRONTEND_BASE_PATH must be a path such as /openrag-fe",
@@ -34,9 +35,10 @@ dotenv.config({
path: path.resolve(process.cwd(), "..", process.env.ENV_FILE || ".env"),
});
-const frontendBasePath = normalizeFrontendBasePath(
- process.env.OPENRAG_FRONTEND_BASE_PATH,
-);
+// Next inlines `basePath` into browser bundles. Image builds use a placeholder
+// that the entrypoint replaces in a writable runtime copy of the assets.
+const RUNTIME_BASE_PATH_PLACEHOLDER =
+ "/NEXT_PUBLIC_BASE_PATH_PLACEHOLDER_a1b2c3d4";
function getAllowedDevOrigins(): string[] {
const allowedDevOrigins = process.env.NEXT_ALLOWED_DEV_ORIGINS;
@@ -54,37 +56,47 @@ function getAllowedDevOrigins(): string[] {
.filter(Boolean);
}
-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
- // (not the port), so a second instance must use a distinct distDir.
- distDir: process.env.NEXT_DIST_DIR || ".next",
- // Increase timeout for API routes
- experimental: {
- proxyTimeout: 300000, // 5 minutes
- },
- async rewrites() {
- return [{ source: "/mcp/:path*", destination: "/api/mcp/:path*" }];
- },
- // Disable built-in image optimization so Next does not require the `sharp`
- // native dependency (and its LGPL libvips binaries). The only <Image> usage
- // is a 32px file-preview thumbnail, which does not benefit from optimization.
- images: {
- unoptimized: true,
- },
- // Ignore TypeScript errors during build
- typescript: {
- ignoreBuildErrors: true,
- },
- // Allow cross-origin requests in development
- allowedDevOrigins: getAllowedDevOrigins(),
+const createNextConfig = (phase: string): NextConfig => {
+ const useRuntimeBasePathPlaceholder =
+ process.env.OPENRAG_FRONTEND_RUNTIME_BASE_PATH === "true";
+ const frontendBasePath =
+ phase !== PHASE_DEVELOPMENT_SERVER && useRuntimeBasePathPlaceholder
+ ? RUNTIME_BASE_PATH_PLACEHOLDER
+ : normalizeFrontendBasePath(process.env.OPENRAG_FRONTEND_BASE_PATH);
+
+ return {
+ // `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,
+ },
+ output: "standalone",
+ // 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
+ // (not the port), so a second instance must use a distinct distDir.
+ distDir: process.env.NEXT_DIST_DIR || ".next",
+ // Increase timeout for API routes
+ experimental: {
+ proxyTimeout: 300000, // 5 minutes
+ },
+ async rewrites() {
+ return [{ source: "/mcp/:path*", destination: "/api/mcp/:path*" }];
+ },
+ // Disable built-in image optimization so Next does not require the `sharp`
+ // native dependency (and its LGPL libvips binaries). The only <Image> usage
+ // is a 32px file-preview thumbnail, which does not benefit from optimization.
+ images: {
+ unoptimized: true,
+ },
+ // Ignore TypeScript errors during build
+ typescript: {
+ ignoreBuildErrors: true,
+ },
+ // Allow cross-origin requests in development
+ allowedDevOrigins: getAllowedDevOrigins(),
+ };
};
-export default nextConfig;
+export default createNextConfig;
diff --git a/kubernetes/helm/openrag/templates/frontend/deployment.yaml b/kubernetes/helm/openrag/templates/frontend/deployment.yaml
index 8fe518361..993a57d69 100644
--- a/kubernetes/helm/openrag/templates/frontend/deployment.yaml
+++ b/kubernetes/helm/openrag/templates/frontend/deployment.yaml
@@ -1,4 +1,8 @@
{{- if .Values.frontend.enabled }}
+{{- $frontendBasePath := .Values.frontend.basePath | trim | trimSuffix "/" }}
+{{- if and $frontendBasePath (not (hasPrefix "/" $frontendBasePath)) }}
+{{- $frontendBasePath = printf "/%s" $frontendBasePath }}
+{{- end }}
apiVersion: apps/v1
kind: Deployment
metadata:
@@ -50,12 +54,19 @@ spec:
# Backend connection (uses internal service name)
- name: OPENRAG_BACKEND_HOST
value: "{{ include "openrag.fullname" . }}-backend"
+ - name: OPENRAG_FRONTEND_BASE_PATH
+ value: {{ .Values.frontend.basePath | quote }}
+ volumeMounts:
+ # The entrypoint copies and patches generated assets here so the
+ # image itself remains usable with readOnlyRootFilesystem: true.
+ - name: frontend-runtime-assets
+ mountPath: /tmp
resources:
{{- toYaml .Values.frontend.resources | nindent 12 }}
{{- if .Values.frontend.livenessProbe.enabled }}
livenessProbe:
httpGet:
- path: /
+ path: {{ $frontendBasePath | default "/" | quote }}
port: http
initialDelaySeconds: {{ .Values.frontend.livenessProbe.initialDelaySeconds }}
periodSeconds: {{ .Values.frontend.livenessProbe.periodSeconds }}
@@ -65,7 +76,7 @@ spec:
{{- if .Values.frontend.readinessProbe.enabled }}
readinessProbe:
httpGet:
- path: /
+ path: {{ $frontendBasePath | default "/" | quote }}
port: http
initialDelaySeconds: {{ .Values.frontend.readinessProbe.initialDelaySeconds }}
periodSeconds: {{ .Values.frontend.readinessProbe.periodSeconds }}
@@ -84,4 +95,7 @@ spec:
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
+ volumes:
+ - name: frontend-runtime-assets
+ emptyDir: {}
{{- end }}
diff --git a/kubernetes/helm/openrag/values.yaml b/kubernetes/helm/openrag/values.yaml
index b36e53095..65a4623b9 100644
--- a/kubernetes/helm/openrag/values.yaml
+++ b/kubernetes/helm/openrag/values.yaml
@@ -441,6 +441,10 @@ backend:
frontend:
enabled: true
+ # Optional URL path below which the frontend is served (for example,
+ # /openrag-fe). Applied when each frontend pod starts; no image rebuild.
+ basePath: ""
+
image:
repository: langflowai/openrag-frontend
tag: "" # Uses global.imageTag if empty