Serving openGym under a subpath works, with or without the prefix reaching the container (#238)

The app's assets were already relative — the shell loads fine from any directory, which is how
the demo lives under /demo/. What assumed the site root was the API call: `fetch('/api/...')`
went to the proxy's own root, where there is nothing to answer it, so behind
`https://example.com/gym/` the app booted and then could not talk to its server.

It now asks its own address instead: `appBase()` reads the directory the app is being served
from, which the router never leaves — every screen is a hash, and a path that is not a file is
sent back to the app's root before React boots. A proxy that strips its prefix (Caddy's
`handle_path`, Traefik's StripPrefix) therefore needs no configuration at all.

For a proxy that passes the prefix through, the web container takes `BASE_PATH=/gym`, rendered
into its nginx config at start-up like the other settings, so it applies to a prebuilt image.
Wired through docker-compose.yml as well — a documented setting the compose file does not pass
on is no setting at all.

Both shapes were checked in containers rather than read: with BASE_PATH empty the shell, the
assets, /api and the deep-path redirect behave exactly as before; with BASE_PATH=/gym all four
work under the prefix and the redirect stays inside it. The first attempt passed at /gym/ and
404'd /gym/assets/app.js, because a regex location outranks the prefix block and never saw its
rewrite — the cache-control blocks carry it too now. The built app was then loaded in a browser
under /gym/ and its own requests go to /gym/api/config and /gym/api/me.

Reported by leon332157.
This commit is contained in:
Duarte Santos committed 2026-09-20 20:16:52 +02:00
1 parent f7b9a80a93
commit 542c3f493a
8 files changed
+124 -6

No files matched your search

+32
View File
@@ -0,0 +1,32 @@
// @vitest-environment happy-dom
// Issue #238: openGym behind a reverse proxy that serves it under a subpath. The assets were
// already relative; the API call was not, so it went to the proxy's own root where nothing
// answers it. The base is read from where the app is being served.
import { describe, it, expect } from 'vitest'
import { appBase } from './api.js'
const at = pathname => appBase({ pathname })
describe('the app knows where it is served from', () => {
it('is the site root for an ordinary deployment', () => {
expect(at('/')).toBe('/')
expect(at('/index.html')).toBe('/')
})
it('keeps the proxy prefix of a subpath deployment', () => {
expect(at('/myGym/')).toBe('/myGym/')
expect(at('/myGym/index.html')).toBe('/myGym/')
expect(at('/a/b/c/')).toBe('/a/b/c/')
})
it('drops a stale deep path rather than inventing a base from it', () => {
// nginx sends these back to the app root before React boots; this is the belt and braces.
expect(at('/myGym/plan/r/x')).toBe('/myGym/plan/r/')
expect(at('/plan')).toBe('/')
})
it('survives a missing or odd location', () => {
expect(appBase(null)).toBe('/')
expect(at('')).toBe('/')
})
})
+22 -1
View File
@@ -15,10 +15,31 @@ let remoteBase = ''
let remoteToken = null
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
/* Where this copy of the app is served from, e.g. "/" or "/myGym/" (issue #238).
*
* The app routes behind the hash and its assets are relative (vite `base: './'`), so the only
* thing that assumed the site root was the API call. A reverse proxy that puts openGym under a
* subpath — and strips that prefix before the container sees it, which is what Caddy's
* `handle_path` and its equivalents do — got `/api/...` at the proxy's own root, where there is
* nothing to answer it.
*
* `location.pathname` is the base because the router never leaves it: every screen is a hash,
* and a path that is not a file is sent back to the app's root before React boots
* (web/nginx.conf.template). Anything after the last slash is therefore index.html or a stale
* deep link, and is dropped.
*/
export function appBase(loc = typeof location !== 'undefined' ? location : null) {
const path = (loc && loc.pathname) || '/'
return path.slice(0, path.lastIndexOf('/') + 1) || '/'
}
export async function api(path, opts) {
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
// A paired phone has an absolute base of its own; everyone else is relative to where the app
// is served, so a subpath deployment reaches its own API instead of the proxy's root.
const url = remoteBase ? remoteBase + path : appBase().replace(/\/$/, '') + path
const r = await fetch(url, Object.assign({}, opts, { headers }))
const data = await r.json().catch(() => ({}))
// The body rides along on the error: a 409 from /api/data carries the server's document.
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; e.data = data; throw e }
+2 -2
View File
@@ -9,7 +9,7 @@ import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, be
import { fmtNum, capWords, fmtDate, todayISO, exCount, DAYN } from '../lib/format.js'
import { beep, vibrate, unlock } from '../lib/sound.js'
import { t, exerciseNameFor } from '../lib/i18n.js'
import { api } from '../lib/api.js'
import { api, appBase } from '../lib/api.js'
import { insertionIndexAfterCurrentUnit, nextUnfinishedUnit, setProgressHighWater, supersetFlowStep, restAfterSet, restOnRecheck, restSecFor, warmupRestSecFor } from '../lib/supersetFlow.js'
import Media from '../components/Media.jsx'
import { startFlow, exercisePicker, exConfigSheet, exerciseDetailSheet, finishWorkout, workoutCompleteSheet, confirmSheet, exerciseNoteSheet, sessionNoteSheet, renameWorkoutSheet, swapActiveWorkoutExercise, barWeightSheet, menuSheet, effortPickerSheet, exerciseHistorySheet, addRoutineToSessionSheet } from '../sheets.jsx'
@@ -964,7 +964,7 @@ function ActiveWorkout() {
return () => {
stopped = true; clearInterval(iv)
// best-effort "left" signal: sendBeacon survives a tab close, fetch covers in-app nav
try { navigator.sendBeacon?.('/api/activity', new Blob([JSON.stringify({ active: false })], { type: 'application/json' })) } catch { /* */ }
try { navigator.sendBeacon?.(appBase().replace(/\/$/, '') + '/api/activity', new Blob([JSON.stringify({ active: false })], { type: 'application/json' })) } catch { /* */ }
api('/api/activity', { method: 'POST', body: JSON.stringify({ active: false }) }).catch(() => {})
}
}, [])