Monitor Website Performance by Self-Host Lighthouse Server

自架 Lighthouse 伺服器實現持續監控網站最佳實踐

前言

在先前的文章提到如何使用 Lighthouse 這款工具監控前端大大小小的最佳實踐,例如:效能、SEO、適用性……等能被客觀測量比較的數值:只要三步驟透過 Lighthouse CI 自動化檢測網站效能,過程中上傳對象設定為 Google 提供的免費暫存伺服器:

upload:
target: 'temporary-public-storage'
# upload options here

雖然很方便但你可能會希望自架 Lighthouse 服務,以便實現:

  1. 蒐集與管理自己的隱私資料
  2. 持續性監控同個網站的檢測資料
  3. 減少依賴第三方伺服器服務

具體來說這篇文章會說明我根據官方文件:The Lighthouse CI Server🔗 實現自架 Lighthouse。

Lighthouse 自建伺服器範例

Docker 自架 Lighthouse 伺服器

官方文件提供了 本地自建🔗Docker🔗 兩種方式,基於這是個簡單的小監測功能沒有什麼太複雜的流量或擴張需求,我是直接將 Docker 部屬上 Zeabur🔗 這樣的 Pass 服務,各平台的操作應該大同小異。

建構 Lighthouse 伺服器

  1. 拿著官方提供的 Docker Image - patrickhulce/lhci-server🔗 到平台上部屬
  2. 根據官方設定設置 /datavolumes 存放永久資料、設置預設 9001 port 對外開放
  3. 使用 npx lhci wizard 指令初始化 Lighthouse 專案填寫基本資料
Terminal window
$ npx lhci wizard # Use the wizard to create a project.
? Which wizard do you want to run? new-project
? What is the URL of your LHCI server? https://your-lhci-server.example.com/
? What would you like to name the project? My Favorite Project
? Where is the project's code hosted? https://github.com/GoogleChrome/lighthouse-ci
Created project My Favorite Project (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)!
Use build token XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX to connect.
Use admin token XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX to manage the project.

連結 Lighthouse 伺服器

專案初始化後最終會拿到 build tokenadmin token,根據官方安全性文件🔗提到:

  • build token:允許使用者將新資料上傳到特定項目,但不允許破壞或編輯任何歷史資料。如果專案是開源的,並且想要收集來自外部貢獻者的拉取請求的 Lighthouse 數據,那麼應該公開。

  • admin token:管理員令牌允許使用者編輯或刪除特定項目的資料。管理員令牌只能與受信任的使用者共用,且絕不能放置在 CI 環境中,即使在有外部貢獻者的開源專案中也是如此。任何擁有管理員令牌的人都可以刪除整個專案的資料。

也就是說只要拿著 build token 就能上傳最新的檢測資料了,來到生成 lighthouse 報告的專案設置當中,重新設置 lighthouse upload 相關的屬性:

lighthouserc.cjs
module.exports = {
ci: {
collect: {
numberOfRuns: 1,
startServerCommand: 'pnpm astro preview',
url: [
'http://localhost:4321/en/',
'http://localhost:4321/en/resume/',
'http://localhost:4321/en/work/',
'http://localhost:4321/en/faq/',
],
},
upload: {
target: 'lhci',
serverBaseUrl: 'https://lhci-weweweb.zeabur.app/',
token: process.env.LHCI_TOKEN,
},
},
};

再調整一下 CI 要使用到的變數,並且到 GitHub Secrets 添加 build tokenLHCI_TOKEN

- name: Run Lighthouse CI
env:
LHCI_TOKEN: ${{ secrets.LHCI_TOKEN }}
run: pnpm dlx @lhci/cli@0.14.x autorun

接著就可以到 Lighthouse 伺服器觀察每一次 CI 提交的資料了。

Lighthouse 結果

總結

對我來說自建 Lighthouse 相較於使用 temporary-public-storagePageSpeed Insights🔗 有一個明顯的好處是能夠長期追蹤專案的各方面最佳實踐,而不只專注於單一次檢測的結果,甚至能抓取不同的 Commit 時機查看每項評分的差距,對前端來說可說是酷炸了,長期檢測下來也能讓團隊對於代碼品質有更高的認知與責任心。