Sub-Store icon indicating copy to clipboard operation
Sub-Store copied to clipboard

Self-hosted frontend: enable gzip compression and proper Cache-Control for static assets

Open githubdulong opened this issue 4 months ago • 4 comments

Problem

When self-hosting Sub-Store (Node.js backend serving the frontend directly), the frontend loads slowly on mobile devices (8+ seconds on LAN) because:

  1. No gzip/brotli compression — The Express static middleware serves main-*.js (800KB) uncompressed. With gzip it's ~258KB.
  2. No long-term caching for hashed assets — All files are served without Cache-Control, so the browser re-downloads everything on each visit, even though filenames already contain content hashes (e.g. main-a8197d84.js).

Suggested Fix

In the standalone frontend Express server (when SUB_STORE_FRONTEND_PATH is set and be_merge is off):

const compression = require('compression');
app.use(compression());

const staticFileMiddleware = express.static(fe_path, {
  setHeaders: (res, filePath) => {
    // Hash files get immutable cache; index.html gets no-store
    if (/[-\.][0-9a-f]{8,}\./.test(filePath)) {
      res.set('Cache-Control', 'public, max-age=31536000, immutable');
    } else {
      res.set('Cache-Control', 'no-store');
    }
  }
});

This also applies to the merge-mode (be_merge) code path.

Impact

  • First load: ~800KB → ~258KB transfer (68% reduction), 8s → 2s on LAN
  • Repeat visits: instant (assets served from browser cache)
  • Zero behavior change for users on CDN deployments (CDN already handles this)

Environment

  • Sub-Store backend v2.36.11
  • Self-hosted on macOS, Node.js v24, Express serving frontend directly on LAN
  • Tested on iOS Safari and desktop Chrome

Workaround

Currently patching sub-store.min.js manually after each update to add compression middleware and setHeaders.

githubdulong avatar Jul 18 '26 15:07 githubdulong

@githubdulong @hyruleboss 有空看看这个吗 怎么感觉不对 不是有pwa那些设置吗🤔

xream avatar Jul 18 '26 15:07 xream

PWA 的 Service Worker 确实能缓存资源,但在局域网自部署场景下有个实际问题:SW 缓存更新不及时容易导致前端白屏(特别是 iOS Safari,对 ES module 的 MIME 校验很严格,旧缓存和新版本混用直接挂)。我这几版老是遇到了白屏。

所以我手动禁用了 SW 来保证每次加载到最新版本。这样一来就完全依赖网络传输了,800KB 的主包在局域网不压缩的话确实要好几秒。

其实如果后端 Express 加个 compression 中间件 + 对 hash 文件设 immutable 缓存就能兼顾两者:浏览器自带的 HTTP 缓存不会像 SW 那样出现版本混乱,而 gzip 也能把首次加载从 8 秒压到 2 秒。

小一宝贝有没有计划在 Node 自部署模式下默认启用这些?或者有更推荐的部署方式?

githubdulong avatar Jul 18 '26 15:07 githubdulong

@githubdulong 1. 我没遇到过... 2. 压缩一般反代加。公网反正都有反代 都会有。局域网根本察觉不到区别吧... 3. 可能加个环境变量用来开启啥的?

明天再跟前端总监一起看看 最近缺少睡眠 不清醒了 sorry

xream avatar Jul 18 '26 16:07 xream

后端: 2.36.12 已更新

xream avatar Jul 19 '26 00:07 xream