feat(frontend): runtime backend URL via /config.js

Stop baking VITE_API_URL into the Vite build so one image can
run against any backend. Container entrypoint
(docker-entrypoint.d/30-frontend-config.sh, auto-run by the
nginx image) writes /usr/share/nginx/html/config.js from the
VITE_API_URL container env at every start; index.html loads
it before the bundle, and agent.ts prefers
window.__APP_CONFIG__ with the build-time env as fallback so
local dev and vite preview behave exactly as before.
public/config.js ships an empty placeholder for non-container
builds. Changing backends is now a restart with new env, no
rebuild.
This commit is contained in:
2026-09-06 12:48:58 -04:00
parent 3e0385d5d9
commit 8b18dc55c8
4 changed files with 36 additions and 1 deletions
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Generates runtime frontend config from container environment.
# Runs automatically at container start via nginx's /docker-entrypoint.d/.
# Lets one image talk to any backend: set VITE_API_URL on the service
# (compose environment or .env) and restart — no rebuild needed.
# The app (src/api/agent.ts) prefers this file, falling back to the
# build-time VITE_API_URL when it is absent (local dev, vite preview).
set -eu
CONFIG_FILE="/usr/share/nginx/html/config.js"
mkdir -p "$(dirname "${CONFIG_FILE}")"
if [ -z "${VITE_API_URL:-}" ]; then
echo "frontend-config: VITE_API_URL not set, writing empty config (build-time env applies)"
printf 'window.__APP_CONFIG__ = {};\n' > "${CONFIG_FILE}"
else
echo "frontend-config: writing config.js with VITE_API_URL=${VITE_API_URL}"
printf 'window.__APP_CONFIG__ = { VITE_API_URL: "%s" };\n' "${VITE_API_URL}" > "${CONFIG_FILE}"
fi
+3
View File
@@ -32,6 +32,9 @@
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!-- Runtime config (backend URL) injected at container start.
See docker-entrypoint.d/30-frontend-config.sh and public/config.js. -->
<script src="/config.js"></script>
<script type="module" src="/src/index.tsx"></script>
<!--
This HTML file is a template.
+6
View File
@@ -0,0 +1,6 @@
// Placeholder replaced at container start by
// docker-entrypoint.d/30-frontend-config.sh, which writes the real
// VITE_API_URL from the container environment. Served as /config.js
// (see index.html). Empty here so local builds fall back to the
// build-time import.meta.env value.
window.__APP_CONFIG__ = {};
+8 -1
View File
@@ -11,7 +11,14 @@ const sleep = (delay: number) => {
setTimeout(resolve, delay)
})
}
axios.defaults.baseURL = import.meta.env.VITE_API_URL
// Backend URL: container runtime config first (/config.js, written from
// VITE_API_URL at container start), build-time env as fallback for dev.
declare global {
interface Window {
__APP_CONFIG__?: { VITE_API_URL?: string }
}
}
axios.defaults.baseURL = window.__APP_CONFIG__?.VITE_API_URL ?? import.meta.env.VITE_API_URL
axios.interceptors.request.use((config) => {
const token = userToken.get()