Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Serving openGym under a subpath works, with or without the prefix reaching the container (#238)
Duarte Santos542c3f493abe
diff --git a/.env.example b/.env.exampleindex 484206512..a7a63a993 100644--- a/.env.example+++ b/.env.example@@ -113,6 +113,13 @@ RP_NAME=openGym# NGINX_PORT=80# BACKEND=api# PORT=3000+#+# Serving openGym under a subpath (https://example.com/gym/)? If your reverse+# proxy strips the prefix before the container sees it, set nothing — the app+# asks its own address for the API. If it passes the prefix through, name it+# here without a trailing slash:+#+# BASE_PATH=/gym# ── Notifications (optional) ───────────────────────────────────────────────# Push works out of the box — nothing to set. VAPID keys are generated on firstdiff --git a/docker-compose.yml b/docker-compose.ymlindex e8849f76d..76690fa9d 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -85,6 +85,10 @@ services:# Empty drops the CF-Connecting-IP header, so a direct client cannot forge the address# the activity log records. Cloudflare users set CF_CONNECTING_IP=$$http_cf_connecting_ip.- CF_CONNECTING_IP=${CF_CONNECTING_IP:-}+ # Subpath deployments behind a proxy that passes its prefix through ("/gym", no trailing+ # slash). Empty serves the app at the site root, which is what it has always done; a proxy+ # that strips the prefix needs nothing set (docs/SELF_HOSTING.md §5).+ - BASE_PATH=${BASE_PATH:-}volumes:- ./media/img:/usr/share/nginx/html/img:ro- ./media/gif:/usr/share/nginx/html/gif:rodiff --git a/docs/SELF_HOSTING.md b/docs/SELF_HOSTING.mdindex 5551f5aa6..e256873fd 100644--- a/docs/SELF_HOSTING.md+++ b/docs/SELF_HOSTING.md@@ -182,6 +182,7 @@ NGINX_PORT=80 # port the web container listens on, inside the contaBACKEND=api # name of the API service that /api is proxied toPORT=3000 # port the API listens on; web proxies to the same valueRESOLVER=127.0.0.11 # DNS nginx resolves BACKEND with — Docker's, unless you are not on Docker+BASE_PATH= # subpath openGym is served under, e.g. /gym — see below; empty = site rootSESSION_DAYS=90 # how long a sign-in lasts```@@ -200,6 +201,40 @@ Note the difference from `VITE_IMG_BASE` / `VITE_GIF_BASE` (see Troubleshooting)build-time values baked into the frontend bundle, and setting them next to `docker compose` doesnothing to an image you pulled.+### Serving openGym under a subpath++openGym can live at `https://example.com/gym/` rather than on a host of its own. Which of the two+setups below you need depends on one thing: whether your reverse proxy strips the prefix before+the container sees the request.++**The proxy strips the prefix** (Caddy's `handle_path`, Traefik's `StripPrefix` middleware,+nginx `proxy_pass` with a trailing slash). Nothing to configure. The app's assets are relative+and it asks its own address for the API, so everything stays inside the prefix on its own:++```caddy+example.com {+ handle_path /gym/* {+ reverse_proxy opengym-web:80+ }+}+```++**The proxy passes the prefix through.** Tell the web container what it is, without a trailing+slash:++```bash+BASE_PATH=/gym+```++That is a start-up setting like the others above, so it works on a prebuilt image. Forward only+the prefix to the container — openGym does not serve itself at the site root as well, and a copy+reached there would look for an API that is not on that path.++Either way, keep `ORIGIN` and `RP_ID` pointing at the address in the browser's bar+(`ORIGIN=https://example.com`, `RP_ID=example.com`). Passkeys key on the host, not the path, so a+subpath changes nothing about section 2 — but it does mean two instances under one hostname share+a passkey scope and can see each other's credentials. Give each its own hostname if that matters.+## 6. BackupsEverything is in `./data`:diff --git a/frontend/src/lib/api-base.test.js b/frontend/src/lib/api-base.test.jsnew file mode 100644index 000000000..aa0dccba6--- /dev/null+++ b/frontend/src/lib/api-base.test.js@@ -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('/')+ })+})diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.jsindex dc15c65ba..5f3a16671 100644--- a/frontend/src/lib/api.js+++ b/frontend/src/lib/api.js@@ -15,10 +15,31 @@ let remoteBase = ''let remoteToken = nullexport 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 }diff --git a/frontend/src/views/Workout.jsx b/frontend/src/views/Workout.jsxindex 91aaf3dc8..6f0c5eafb 100644--- a/frontend/src/views/Workout.jsx+++ b/frontend/src/views/Workout.jsx@@ -9,7 +9,7 @@ import { effectiveRoutines, effectiveRoutineIds, lastEntryFor, bestWeightFor, beimport { 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(() => {})}}, [])diff --git a/web/Dockerfile b/web/Dockerfileindex c92d09eab..db9c761e9 100644--- a/web/Dockerfile+++ b/web/Dockerfile@@ -58,6 +58,10 @@ ENV RESOLVER=127.0.0.11# front. Defined here too, not just in compose, so the template always renders for anyone# running the prebuilt image from their own compose file.ENV CF_CONNECTING_IP=""+# Subpath deployments behind a reverse proxy that does NOT strip its prefix: "/gym", no trailing+# slash. Empty (the default) serves the app at the root exactly as before. A proxy that strips+# the prefix needs nothing here — the app derives the API address from its own URL.+ENV BASE_PATH=""# Probe the port nginx was actually told to listen on (NGINX_PORT is configurable, so a# hardcoded http://localhost/ breaks on any instance that changed it), and address it asdiff --git a/web/nginx.conf.template b/web/nginx.conf.templateindex 2cd22ad7d..e3c8b8df9 100644--- a/web/nginx.conf.template+++ b/web/nginx.conf.template@@ -19,7 +19,7 @@ server {# `^~` so this prefix beats the regex locations below: without it a request for a path such# as /api/anything.json would be matched by the \.(js|css|json|html)$ block instead and be# looked for on disk rather than proxied.- location ^~ /api/ {+ location ^~ ${BASE_PATH}/api/ {# Match the API's own body limit (MAX_BODY in api/server.js): the whole workout history# travels in one PUT /api/data, and nginx's 1 MiB default would answer 413 here before the# API ever saw it — a sync that silently stops once the history grows past 1 MiB.@@ -59,16 +59,28 @@ server {# under that path and 404'd — blank, with a 200. Send the browser to the root instead. The# query string travels along; the hash never reaches the server anyway. Relative Location so# the redirect keeps the scheme and host the reverse proxy in front presented, not nginx's own.- location / {+ #+ # BASE_PATH (default empty) is for a reverse proxy that serves openGym under a subpath and+ # passes that prefix through — "/gym", no trailing slash. A proxy that strips the prefix+ # before the container sees it needs nothing set here: the app asks its own address for the+ # API (lib/api.js appBase), so the call carries whatever prefix the browser is using.+ location ${BASE_PATH}/ {+ # `rewrite ... break` rather than `alias`: try_files inside an aliased prefix location is+ # a long-standing nginx trap (it still resolves the untranslated URI). With BASE_PATH+ # empty this rewrite is an identity and the block behaves exactly as it always has.+ rewrite ^${BASE_PATH}/(.*)$ /$1 break;try_files $uri $uri/ @root;}location @root {absolute_redirect off;- return 302 /$is_args$args;+ return 302 ${BASE_PATH}/$is_args$args;}# App shell: always revalidate so updates show up immediatelylocation ~* \.(js|css|json|html)$ {+ # A regex location wins over the prefix block above, so it never saw its rewrite and+ # looked for the file under the prefix on disk. Same identity-when-empty rewrite here.+ rewrite ^${BASE_PATH}/(.*)$ /$1 break;add_header Cache-Control "no-cache, must-revalidate";add_header X-Frame-Options "DENY" always;add_header X-Content-Type-Options "nosniff" always;@@ -78,6 +90,9 @@ server {# Exercise images/GIFs never change → cache hardlocation ~* \.(png|jpg|jpeg|gif|ico|svg|woff|woff2|webp|avif)$ {+ # A regex location wins over the prefix block above, so it never saw its rewrite and+ # looked for the file under the prefix on disk. Same identity-when-empty rewrite here.+ rewrite ^${BASE_PATH}/(.*)$ /$1 break;expires 30d;add_header Cache-Control "public, max-age=2592000, immutable";add_header X-Frame-Options "DENY" always;