Skip to content

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.

Subpath deployments: the service worker no longer caches the API and replays an old copy offline (#238)

Duarte Santosb9427d914bf9
diff --git a/frontend/public/sw.js b/frontend/public/sw.js
index 18d892261..b3599d72d 100644
--- a/frontend/public/sw.js
+++ b/frontend/public/sw.js
@@ -101,10 +101,17 @@ self.addEventListener('pushsubscriptionchange', e => {
})())
})
+// The API sits next to the app, wherever the app is served: /api/ at the site root, /myGym/api/
+// under a subpath (#238). Matching '/api/' alone let a subpath deployment's data answers into
+// the network-first branch below, which cached them and handed an old document back as a 200
+// once the network was gone — the page then took it for the server's word. The Cache API ignores
+// the API's own `Cache-Control: no-store`, so the worker has to know to stay out of the way.
+const API = (() => { try { return new URL('api/', location.href).pathname } catch { return '/api/' } })()
+
self.addEventListener('fetch', e => {
const url = new URL(e.request.url)
if (e.request.method !== 'GET' || url.origin !== location.origin) return
- if (url.pathname.startsWith('/api/')) return // never cache auth/data
+ if (url.pathname.startsWith('/api/') || url.pathname.startsWith(API)) return // never cache auth/data
const isMedia = url.pathname.includes('/img/') || url.pathname.includes('/gif/')
if (isMedia) {
diff --git a/frontend/src/lib/sw-subpath.test.js b/frontend/src/lib/sw-subpath.test.js
new file mode 100644
index 000000000..c28cd9690
--- /dev/null
+++ b/frontend/src/lib/sw-subpath.test.js
@@ -0,0 +1,69 @@
+// @vitest-environment node
+
+/* The worker leaves the API alone under a subpath too (#238). Its "never cache auth/data" guard
+ * used to match '/api/' at the site root only, so under /myGym/ every GET of the data and of its
+ * revision went through the network-first branch: each good answer was cached, and with no
+ * network the page was handed the cached, older document as a 200. The store took that for the
+ * server's answer — a rev check cleared the offline banner and a pull adopted the old copy.
+ * public/sw.js is evaluated as-is against a minimal worker environment. */
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+
+const SW = readFileSync(fileURLToPath(new URL('../../public/sw.js', import.meta.url)), 'utf8')
+
+function worker(scriptUrl) {
+ const handlers = {}
+ const store = new Map()
+ const cache = {
+ put: async (req, res) => { store.set(typeof req === 'string' ? req : req.url, res) },
+ match: async req => store.get(typeof req === 'string' ? req : req.url),
+ add: async () => {},
+ }
+ const env = {
+ self: { addEventListener: (t, f) => { handlers[t] = f }, skipWaiting: () => {}, clients: { claim: () => {} }, registration: {} },
+ caches: { open: async () => cache, keys: async () => [], delete: async () => true, match: async req => store.get(typeof req === 'string' ? req : req.url) },
+ location: new URL(scriptUrl),
+ net: { up: true, body: null },
+ store,
+ }
+ env.fetch = async () => {
+ if (!env.net.up) throw new TypeError('Failed to fetch')
+ return new Response(JSON.stringify(env.net.body), { status: 200, headers: { 'content-type': 'application/json' } })
+ }
+ new Function('self', 'caches', 'fetch', 'location', SW)(env.self, env.caches, env.fetch, env.location)
+ env.get = async url => {
+ let responded = null
+ handlers.fetch({ request: { url, method: 'GET', mode: 'cors' }, respondWith: p => { responded = p } })
+ if (!responded) return { intercepted: false }
+ const res = await responded
+ await new Promise(r => setTimeout(r, 5)) // the cache.put runs after the response is handed over
+ return { intercepted: true, res }
+ }
+ return env
+}
+
+describe('the service worker and the API', () => {
+ it('leaves the API alone at the site root', async () => {
+ const env = worker('https://gym.example.com/sw.js')
+ expect((await env.get('https://gym.example.com/api/data')).intercepted).toBe(false)
+ expect((await env.get('https://gym.example.com/api/data/rev')).intercepted).toBe(false)
+ })
+
+ it('leaves the API alone under a subpath, so an old document is never replayed offline', async () => {
+ const env = worker('https://example.com/myGym/sw.js')
+ env.net.body = { state: { workouts: [{ id: 'w1' }] }, rev: 5 }
+ expect((await env.get('https://example.com/myGym/api/data')).intercepted).toBe(false)
+ expect((await env.get('https://example.com/myGym/api/data/rev')).intercepted).toBe(false)
+ expect(env.store.size).toBe(0)
+ })
+
+ it('still serves the app itself from the cache under that subpath', async () => {
+ const env = worker('https://example.com/myGym/sw.js')
+ env.net.body = { app: true }
+ expect((await env.get('https://example.com/myGym/manifest.json')).intercepted).toBe(true)
+ env.net.up = false
+ const offline = await env.get('https://example.com/myGym/manifest.json')
+ expect(offline.res.status).toBe(200)
+ })
+})