### Install NodeJS and Google Chrome Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md Installs NodeJS and Google Chrome stable on Debian-based systems using apt-get. This is a prerequisite for running Lighthouse CI. ```bash sudo apt-get update sudo apt-get install -y nodejs google-chrome-stable ``` -------------------------------- ### Create a New Lighthouse CI Project Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This snippet demonstrates how to install the Lighthouse CI CLI and use the `lhci wizard` to create a new project. It requires `curl` and `npm` to be installed. The wizard prompts for server URL, project name, and code hosting URL, outputting build and admin tokens. ```bash curl https://your-lhci-server.example.com/version # Make sure you can connect to your server. 0.x.x npm install -g @lhci/cli@0.15.x # Install the Lighthouse CI CLI. Installing... 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. ``` -------------------------------- ### Configure GitHub Actions for Lighthouse CI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This YAML configuration sets up a GitHub Actions workflow to run Lighthouse CI. It checks out the code, sets up Node.js, installs dependencies, and runs the Lighthouse CI command, using a GitHub App token for authentication. ```yaml name: CI on: [push] jobs: lhci: name: Lighthouse runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: ref: ${{ github.event.pull_request.head.sha }} - name: Use Node.js 16.x uses: actions/setup-node@v3 with: node-version: 16.x - name: npm install, build run: | npm install npm run build - name: run Lighthouse CI run: | npm install -g @lhci/cli@0.15.x lhci autorun env: LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }} ``` -------------------------------- ### Start Custom Local Server with http-server (Bash) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/complex-setup.md A bash script snippet to start a local development server using `http-server` in the background for serving static files from the './dist' directory. ```bash #!/bin/bash # Start a custom local development server (in a background process) # Protip: deploy your code to a web-accessible staging server instead for more realistic performance metrics npx http-server -p 9000 ./dist & # ... (run lighthouse ci) # Clean up the development server kill $! ``` -------------------------------- ### Complete CI Workflow Example (GitHub Actions) Source: https://context7.com/googlechrome/lighthouse-ci/llms.txt A comprehensive GitHub Actions workflow demonstrating the integration of Lighthouse CI. This workflow checks out code, sets up Node.js, installs dependencies, builds the project, installs the LHCI CLI, and runs the `lhci autorun` command. It also shows how to upload Lighthouse reports as artifacts. ```yaml name: Lighthouse CI on: push: branches: [main] pull_request: branches: [main] jobs: lighthouse: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 # Full history for ancestor detection - name: Setup Node.js uses: actions/setup-node@v4 with: node-version: 18 cache: 'npm' - name: Install dependencies run: npm ci - name: Build project run: npm run build - name: Install Lighthouse CI run: npm install -g @lhci/cli@0.15.x - name: Run Lighthouse CI run: lhci autorun env: LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }} LHCI_TOKEN: ${{ secrets.LHCI_TOKEN }} # Optional: Upload artifacts - name: Upload Lighthouse reports uses: actions/upload-artifact@v3 if: always() with: name: lighthouse-reports path: .lighthouseci/ retention-days: 30 ``` -------------------------------- ### Configure GitHub Actions for Lighthouse CI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This snippet shows how to configure a GitHub Actions workflow to run Lighthouse CI. It checks out the code, sets up Node.js, installs dependencies, builds the project, and then installs and runs Lighthouse CI. ```yaml name: CI on: [push] jobs: lhci: name: Lighthouse runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Use Node.js 16.x uses: actions/setup-node@v3 with: node-version: 16.x - name: npm install, build run: | npm install npm run build - name: run Lighthouse CI run: | npm install -g @lhci/cli@0.15.x lhci autorun ``` -------------------------------- ### Start Lighthouse CI Server with SQL Storage Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md These examples demonstrate how to start the Lighthouse CI server with different SQL storage configurations. The first command sets a local SQLite database path, while the second configures a PostgreSQL database using a connection URL. ```bash lhci server --storage.sqlDatabasePath=./lhci.db ``` ```bash lhci server --storage.sqlDialect=postgres --storage.sqlConnectionUrl="postgres://user@localhost/lighthouse_ci_db" ``` -------------------------------- ### Configure Travis CI for Lighthouse CI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This configuration sets up Travis CI to run Lighthouse CI. It specifies the Node.js version, installs Chrome, installs the Lighthouse CI CLI, builds the project, and then executes 'lhci autorun'. ```yaml language: node_js node_js: v16 addons: chrome: stable before_install: - npm install -g @lhci/cli@0.15.x script: - npm run build - lhci autorun ``` -------------------------------- ### Lighthouse CI Collect Command Examples (Bash) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md These bash examples demonstrate various ways to use the `lhci collect` command. They cover basic usage with specified runs and URLs, starting a custom webserver, using the built-in static server, auditing specific URLs, running on multiple URLs, and integrating with a Puppeteer script for login. ```bash # Basic usage lhci collect --numberOfRuns=5 --url=https://example.com ``` ```bash # Have LHCI start a server before running lhci collect --start-server-command="yarn serve" --url=http://localhost:8080/ ``` ```bash # Have LHCI use the built-in server on a static directory lhci collect --staticDistDir=./dist ``` ```bash # Have LHCI use the built-in server and audit a specific URL lhci collect --staticDistDir=./public --url=http://localhost/products/pricing/ ``` ```bash # Run on multiple URLs lhci collect --url=https://example-1.com --url=https://example-2.com ``` ```bash # Have LHCI start a server and login with puppeteer before running lhci collect --start-server-command="yarn serve" --url=http://localhost:8080/ --puppeteer-script=./path/to/login-with-puppeteer.js ``` -------------------------------- ### Run Lighthouse CI with npm scripts in job.sh Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md A bash script to install npm dependencies, build the project, set Chrome path and build URL environment variables, install Lighthouse CI CLI globally, and run an audit. It assumes a standard NodeJS project structure. ```bash #!/bin/bash set -euxo pipefail npm install npm run build export CHROME_PATH=$(which google-chrome-stable) export LHCI_BUILD_CONTEXT__EXTERNAL_BUILD_URL="$BUILD_URL" npm install -g @lhci/cli@0.15.x lhci autorun ``` -------------------------------- ### Google Cloud Build Configuration for Lighthouse CI (cloudbuild.yml) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md Defines build steps for Google Cloud Build, including installing dependencies, building the project, and running Lighthouse CI. It uses a specific Docker image with Node and Chrome and sets environment variables for branch name. ```yaml steps: - id: 'install' args: ['npm', 'ci'] name: node:16-alpine - id: 'build' waitFor: ['install'] name: node:16-alpine args: ['npm', 'run', 'build'] - id: 'lighthouse' waitFor: ['build'] name: cypress/browsers:node16.17.0-chrome106 entrypoint: '/bin/sh' args: ['-c', 'npm install -g @lhci/cli@0.15.x && lhci autorun --failOnUploadFailure'] env: - 'LHCI_BUILD_CONTEXT__CURRENT_BRANCH=$BRANCH_NAME' options: machineType: 'N1_HIGHCPU_8' ``` -------------------------------- ### Configure Jenkins for Lighthouse CI (Ubuntu) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This bash script prepares a Jenkins environment on Ubuntu for Lighthouse CI. It adds Google Chrome's apt repository and key, and then adds Node.js's repository before proceeding with other build steps. ```bash #!/bin/bash set -euxo pipefail # Add Chrome's apt-key echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" | sudo tee -a /etc/apt/sources.list.d/google.list wget -q -O - https://dl.google.com/linux/linux_signing_key.pub | sudo apt-key add - # Add Node's apt-key curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash - ``` -------------------------------- ### Configure GitLab CI for Lighthouse CI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This configuration for GitLab CI includes a `.lighthouserc.js` file to specify Chrome flags and upload targets, and a `.gitlab-ci.yml` file to install dependencies, build the project, install Lighthouse CI, and run 'lhci autorun' with specific parameters. ```js module.exports = { ci: { collect: { settings: {chromeFlags: '--no-sandbox'}, }, upload: { target: 'temporary-public-storage', }, }, }; ``` ```yaml image: cypress/browsers:node16.17.0-chrome106 lhci: script: - npm install - npm run build - npm install -g @lhci/cli@0.15.x - lhci autorun --upload.target=temporary-public-storage --collect.settings.chromeFlags="--no-sandbox" || echo "LHCI failed!" ``` -------------------------------- ### Start Lighthouse CI Server with Basic Auth Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md This command shows how to start the Lighthouse CI server with basic HTTP authentication enabled. It specifies a username and password that will be required for all requests to the server's UI and API. ```bash lhci server --storage.sqlDatabasePath=./lhci.db --basicAuth.username="customuser" --basicAuth.password="LighthouseRocks" ``` -------------------------------- ### Configure Circle CI for Lighthouse CI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This snippet demonstrates how to configure Circle CI for Lighthouse CI. It uses a Node.js Docker image with Chrome, checks out the code, installs Chrome, installs dependencies, builds the project, installs the Lighthouse CI CLI globally, and runs 'lhci autorun'. ```yaml version: 2.1 orbs: browser-tools: circleci/browser-tools@1.2.3 jobs: build: docker: - image: cimg/node:16.13-browsers working_directory: ~/your-project steps: - checkout - browser-tools/install-chrome - run: npm install - run: npm run build - run: sudo npm install -g @lhci/cli@0.15.x - run: lhci autorun ``` -------------------------------- ### Run Lighthouse CI Commands (Bash) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/complex-setup.md A bash script demonstrating the installation and execution of Lighthouse CI commands, including `healthcheck`, `collect` for a specific URL, and `assert` with a recommended preset. ```bash #!/bin/bash # ... (build condition check) # ... (server setup) # Install Lighthouse CI # If you're already using node to manage your project, add it to your package.json `devDependencies` instead to skip this step. npm install -g @lhci/cli@0.15.x # Run a healthcheck to make sure everything looks good before we run collection. lhci healthcheck --fatal # Collect Lighthouse reports for our URL. lhci collect --url=http://localhost:9000/index.html # Assert that the reports look good, this command can be configured to ease your Lighthouse transition. lhci assert --preset="lighthouse:recommended" EXIT_CODE=$? # ... (kill server) exit $EXIT_CODE ``` -------------------------------- ### Advanced Lighthouse CI Configuration with YAML Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md An advanced configuration example for Lighthouse CI using YAML format. It specifies collection settings like the number of runs and server start command, assertion presets and custom assertions, and upload targets with server base URLs. This demonstrates a comprehensive setup for CI/CD pipelines. ```yaml ci: collect: numberOfRuns: 5 startServerCommand: rails server -e production url: - http://localhost:3000/ - http://localhost:3000/pricing - http://localhost:3000/support assert: preset: lighthouse:recommended assertions: offscreen-images: 'off' uses-webp-images: 'off' color-contrast: 'off' first-contentful-paint: - error - maxNumericValue: 2000 aggregationMethod: optimistic interactive: - error - maxNumericValue: 5000 aggregationMethod: optimistic upload: target: lhci serverBaseUrl: https://lhci.example.com ``` -------------------------------- ### Install LHCI CLI and Server for Local Use Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/server.md Installs the Lighthouse CI command-line interface and server packages as development dependencies, along with SQLite support. ```bash npm install -D @lhci/cli @lhci/server sqlite3 ``` -------------------------------- ### Lighthouse CI Server REST API Examples Source: https://context7.com/googlechrome/lighthouse-ci/llms.txt Examples of using curl to interact with the Lighthouse CI server's REST API for managing projects and builds. These commands cover listing, retrieving, creating, and deleting projects and builds, as well as fetching associated data like runs and statistics. ```bash # List all projects curl http://localhost:9001/v1/projects # Get project by slug curl http://localhost:9001/v1/projects/slug:my-project # Create a new project curl -X POST http://localhost:9001/v1/projects \ -H "Content-Type: application/json" \ -d '{"name": "My Project", "externalUrl": "https://github.com/org/repo"}' # Get builds for a project curl "http://localhost:9001/v1/projects/{projectId}/builds?limit=10&branch=main" # Get a specific build curl http://localhost:9001/v1/projects/{projectId}/builds/{buildId} # Get ancestor build (for comparison) curl http://localhost:9001/v1/projects/{projectId}/builds/{buildId}/ancestor # Get runs for a build curl "http://localhost:9001/v1/projects/{projectId}/builds/{buildId}/runs?representative=true" # Get statistics for a build curl http://localhost:9001/v1/projects/{projectId}/builds/{buildId}/statistics # Get branches for a project curl http://localhost:9001/v1/projects/{projectId}/branches # Get URLs audited in a project curl http://localhost:9001/v1/projects/{projectId}/urls # Delete a build (requires admin token) curl -X DELETE http://localhost:9001/v1/projects/{projectId}/builds/{buildId} \ -H "x-lhci-admin-token: YOUR_ADMIN_TOKEN" # Delete a project (requires admin token) curl -X DELETE http://localhost:9001/v1/projects/{projectId} \ -H "x-lhci-admin-token: YOUR_ADMIN_TOKEN" ``` -------------------------------- ### Configure Lighthouse CI for Custom Servers (.lighthouserc.js) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md Adapts Lighthouse CI configuration for sites requiring a custom server. It includes `startServerCommand` to launch the server and `url` to specify the target URLs for auditing. ```javascript module.exports = { ci: { collect: { url: ['http://localhost:3000/'], startServerCommand: 'rails server -e production', }, upload: { target: 'temporary-public-storage', }, }, }; ``` -------------------------------- ### Start Lighthouse CI Server Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md This command starts the Lighthouse CI server. It accepts various options to configure logging level, port, storage methods (SQL with dialect and path/URL), authentication, and more. The server is typically run on infrastructure rather than within a build process. ```bash Run Lighthouse CI server Options: --logLevel [string] [choices: "silent", "verbose"] [default: "verbose"] --port, -p [number] [default: 9001] --storage.storageMethod [string] [choices: "sql"] [default: "sql"] --storage.sqlDialect [string] [choices: "sqlite", "postgres", "mysql"] [default: "sqlite"] --storage.sqlDatabasePath The path to a SQLite database on disk. --storage.sqlConnectionUrl The connection url to a postgres or mysql database. --storage.sqlConnectionSsl Whether the SQL connection should force use of SSL [boolean] [default: false] --storage.sqlDangerouslyResetDatabase Whether to force the database to the required schema. WARNING: THIS WILL DELETE ALL DATA [boolean] [default: false] --storage.sqlMigrationOptions.tableName Use a different Sequelize table name. [string] --basicAuth.username The username to protect the server with HTTP Basic Authentication. [string] --basicAuth.password The password to protect the server with HTTP Basic Authentication. [string] ``` -------------------------------- ### Configure Lighthouse CI Assertions (Recommended Preset) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This JavaScript configuration file sets up Lighthouse CI to use a recommended preset for assertions. This will automatically assert a predefined set of Lighthouse audits. ```javascript module.exports = { ci: { // ... assert: { preset: 'lighthouse:recommended', }, // ... }, }; ``` -------------------------------- ### Interactive Project Setup (CLI) Source: https://context7.com/googlechrome/lighthouse-ci/llms.txt The `lhci wizard` command provides an interactive interface for setting up Lighthouse CI projects and managing server tokens. It allows for creating new projects and resetting build or admin tokens. ```bash # Run wizard (interactive prompts) lhci wizard # Wizard options: # - new-project: Create a new project on the server # - reset-build-token: Reset the build token for a project # - reset-admin-token: Reset the admin token for a project ``` -------------------------------- ### Install LHCI Server and SQLite Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/server.md Installs the necessary packages for the LHCI server and SQLite database support using npm. ```bash npm install @lhci/server sqlite3 ``` -------------------------------- ### Static Directory File Discovery Depth Example (Text) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md This text example illustrates the directory structure and how `staticDirFileDiscoveryDepth` affects URL discovery. It shows nested folders and their corresponding depth levels, indicating how Lighthouse will traverse the directory to find HTML files for auditing. ```text public/ ├── index.html #level 0 ├── contact/ │ └── index.html #level 1 ├── projects/ │ ├──index.html #level 1 │ └── crisis/ │ ├──index.html #level 2 │ └── earthquake/ │ └── index.html #level 3 ``` -------------------------------- ### Configuring Server Start Command for Lighthouse CI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md If Lighthouse CI cannot automatically detect your static site's build directory, it looks for a custom npm script named 'serve:lhci' in your package.json to start your web server. This allows autorun to manage the server process during collection. ```json { "scripts": { "serve:lhci": "NODE_ENV=production npm run server" } } ``` -------------------------------- ### Start LHCI Server with SQLite Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/server.md Starts the LHCI server programmatically using Node.js, configuring it to use SQLite for storage. It listens on a port specified by the PORT environment variable. ```javascript const {createServer} = require('@lhci/server'); console.log('Starting server...');createServer({ port: process.env.PORT, storage: { storageMethod: 'sql', sqlDialect: 'sqlite', sqlDatabasePath: '/path/to/db.sql', }, }).then(({port}) => console.log('LHCI listening on port', port)); ``` -------------------------------- ### Run LHCI Server Locally via CLI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/server.md Starts the LHCI server using the npx command, configuring it to use SQLite for storage and specifying the database file path. ```bash npx lhci server --storage.storageMethod=sql --storage.sqlDialect=sqlite --storage.sqlDatabasePath=./db.sql ``` -------------------------------- ### Run Lighthouse CI Script (Bash) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/complex-setup.md A bash script to execute Lighthouse CI commands, including a check to ensure it runs only once per build, installs the CLI, performs a health check, collects results, and asserts against a preset. ```bash #!/bin/bash # NOTE: This step only required for matrix builds, see "Create a run-lhci script" for more details. if [[ "$TRAVIS_NODE_VERSION" != "10" ]]; then echo "Only run Lighthouse CI once per build, node version is not the selected version."; exit 0; fi npm run deploy npm install -g @lhci/cli@0.15.x lhci healthcheck --fatal lhci collect --url=http://localhost:9000/index.html lhci assert --preset="lighthouse:recommended" EXIT_CODE=$? kill $! exit $EXIT_CODE ``` -------------------------------- ### Travis CI Configuration (YAML) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/complex-setup.md YAML configuration for Travis CI to set up the build environment, specifying the operating system, Node.js version, and Chrome addon. ```yaml dist: xenial language: node_js node_js: - '10' addons: chrome: stable ``` -------------------------------- ### Run Lighthouse CI Script with Matrix Build Check (Bash) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/complex-setup.md A bash script for Lighthouse CI that includes a condition to ensure it runs only once in a matrix build environment, checking the TRAVIS_NODE_VERSION. ```bash #!/bin/bash # Example if your travis build runs a matrix like... # matrix: # - 18 # - 16 if [[ "$TRAVIS_NODE_VERSION" != "18" ]]; then echo "Only run Lighthouse CI once per build, node version is not the selected version."; exit 0; fi # ... ``` -------------------------------- ### Run Lighthouse CI Wizard Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md This bash command initiates an interactive wizard for various Lighthouse CI tasks. The wizard can guide users through setting up new projects or resetting server tokens. Resetting tokens requires server configuration and direct database write access. ```bash lhci wizard ? Which wizard do you want to run? (Use arrow keys) ❯ new-project reset-build-token reset-admin-token ``` -------------------------------- ### Configure Lighthouse CI Autorun with Specific Options Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md Demonstrates how to use `lhci autorun` with prefixed options to control child commands. The examples show setting the number of runs for `collect` and the target for `upload`, emphasizing the `=` syntax for atomic arguments. ```bash lhci autorun --collect.numberOfRuns=5 lhci autorun --upload.target=temporary-public-storage ``` -------------------------------- ### Travis CI Script Execution (YAML) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/complex-setup.md YAML configuration for Travis CI to define the script execution order, including building the site, running tests, and executing the Lighthouse CI script. ```yaml script: - npm run build # build your site - npm test # run normal tests - ./scripts/run-lhci.sh # run lighthouse ci ``` -------------------------------- ### Run Lighthouse CI Server (CLI) Source: https://context7.com/googlechrome/lighthouse-ci/llms.txt The `lhci server` command starts the Lighthouse CI server for storing historical data and viewing reports. It supports various SQL databases (SQLite, PostgreSQL), HTTP basic authentication, and custom ports. ```bash # Start with SQLite database lhci server --storage.sqlDatabasePath=./lhci.db # Start with PostgreSQL lhci server --storage.sqlDialect=postgres --storage.sqlConnectionUrl="postgres://user:pass@localhost/lhci" # With HTTP Basic Authentication lhci server --storage.sqlDatabasePath=./lhci.db --basicAuth.username="admin" --basicAuth.password="secret" # Custom port lhci server --port=9001 --storage.sqlDatabasePath=./lhci.db ``` -------------------------------- ### Create and Configure LHCI Server Programmatically (Node.js) Source: https://context7.com/googlechrome/lighthouse-ci/llms.txt Demonstrates how to create a simple LHCI server and an advanced server with custom middleware using the @lhci/server package in Node.js. It covers basic server creation with SQL storage and advanced setup with Express, custom authentication, and additional endpoints. ```javascript const { createServer, createApp } = require('@lhci/server'); // Simple server creation async function startSimpleServer() { const { port, close, storageMethod } = await createServer({ port: 9001, storage: { storageMethod: 'sql', sqlDialect: 'sqlite', sqlDatabasePath: './lhci.db', }, }); console.log(`LHCI server listening on port ${port}`); // Graceful shutdown process.on('SIGTERM', async () => { await close(); process.exit(0); }); } // Advanced: Custom middleware with Express const express = require('express'); async function startCustomServer() { const app = express(); const { app: lhciApp, storageMethod } = await createApp({ storage: { storageMethod: 'sql', sqlDialect: 'postgres', sqlConnectionUrl: process.env.DATABASE_URL, sqlConnectionSsl: true, }, }); // Custom authentication middleware app.use((req, res, next) => { const apiKey = req.headers['x-api-key']; if (apiKey !== process.env.API_KEY) { return res.status(401).json({ error: 'Unauthorized' }); } next(); }); // Mount LHCI app app.use(lhciApp); // Custom endpoints app.get('/custom/health', (req, res) => { res.json({ status: 'healthy', timestamp: new Date().toISOString() }); }); app.listen(9001, () => { console.log('Custom LHCI server listening on port 9001'); }); } ``` -------------------------------- ### Run LHCI Server with Docker (Bash) Source: https://context7.com/googlechrome/lighthouse-ci/llms.txt Instructions for deploying the Lighthouse CI server using Docker. This includes creating a Docker volume for persistent data, running the server container with specified ports and environment variables for basic authentication, and commands to view logs and stop the server. ```bash # Create volume for persistent data docker volume create lhci-data # Run LHCI server container docker container run \ --publish 9001:9001 \ --mount='source=lhci-data,target=/data' \ --env LHCI_BASIC_AUTH_USERNAME=admin \ --env LHCI_BASIC_AUTH_PASSWORD=secretpassword \ --detach \ --name lhci-server \ patrickhulce/lhci-server # View logs docker logs -f lhci-server # Stop server docker stop lhci-server ``` -------------------------------- ### Configure Lighthouse CI for Temporary Public Storage Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This configuration file sets up Lighthouse CI to upload reports to temporary public storage. It requires no external dependencies and is placed at the root of your repository. ```javascript module.exports = { ci: { upload: { target: 'temporary-public-storage', }, }, }; ``` -------------------------------- ### Configure Lighthouse CI for Static Sites (.lighthouserc.js) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md Modifies the Lighthouse CI configuration for static sites by specifying the directory containing HTML files using `staticDistDir`. This is used when a build step is not required. ```javascript module.exports = { ci: { collect: { staticDistDir: './', }, upload: { target: 'temporary-public-storage', }, }, }; ``` -------------------------------- ### Configure Lighthouse CI Assertions (Custom Audits) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This JavaScript configuration file demonstrates how to customize Lighthouse CI assertions by disabling specific audits. This is useful when certain audits fail and need to be temporarily ignored or addressed later. ```javascript module.exports = { ci: { // ... assert: { preset: 'lighthouse:recommended', assertions: { 'uses-rel-preload': 'off', 'uses-rel-preconnect': 'off', }, }, // ... }, }; ``` -------------------------------- ### Configure Lighthouse CI for Google Cloud Build (.lighthouserc.js) Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md Configuration file for Lighthouse CI, specifying Chrome flags to disable the sandbox for environments like Docker or Cloud Build, and setting the upload target to temporary public storage. ```javascript module.exports = { ci: { collect: { settings: {chromeFlags: '--no-sandbox'}, }, upload: { target: 'temporary-public-storage', }, }, }; ``` -------------------------------- ### Configure Lighthouse CI Upload Settings Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/getting-started.md This JavaScript configuration file (`lighthouserc.js`) sets up the Lighthouse CI client to upload reports to a specified server. It requires the server URL and a build token. The token can also be provided via the `LHCI_TOKEN` environment variable for better security. ```javascript module.exports = { ci: { upload: { target: 'lhci', serverBaseUrl: 'https://your-lhci-server-url.example.com', token: 'Your *build token* goes here', // could also use LHCI_TOKEN variable instead }, }, }; // NOTE: If you run a matrix of environments in your tests, make sure you only run `lhci autorun` _ONCE_ per build. The Lighthouse CI server will only accept a single upload per hash and future attempts to upload data for that hash will be rejected. ``` -------------------------------- ### List Projects with jq Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md This command uses curl to fetch a list of projects from the Lighthouse CI server API and jq to extract and display the name and slug of each project. This is useful for identifying the `projectSlug` required for other configurations. ```bash curl http://localhost:9001/v1/projects | jq '.[] |.name,.slug' ``` -------------------------------- ### Non-NodeJS Development Server Configuration Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md Sets up Lighthouse CI to collect data from a development server not running on Node.js. It specifies the command to start the server and the URLs to audit. ```jsonc { "ci": { "collect": { "startServerCommand": "rails server -e production", "url": [ "http://localhost:3000/", "http://localhost:3000/pricing", "http://localhost:3000/support" ] } } } ``` -------------------------------- ### Define URL Replacement Patterns for LHCI Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/configuration.md This example shows how to configure URL replacement patterns in Lighthouse CI using a specific format. These patterns are used to mask differences in URLs for display or to treat them as the same for diff comparisons and status check labels. The format is `s{DELIMITER}{SEARCH_REGEX}{DELIMITER}{REPLACEMENT}{DELIMITER}{SEARCH_REGEX_FLAGS}`. ```regex s/Foo/Bar/g ``` ```regex s/v\d+/VERSION/i ``` ```regex s#(//.*?)/.*$#$1/replaceThePath# ``` -------------------------------- ### LHCI Server Configuration with Docker Compose Source: https://github.com/googlechrome/lighthouse-ci/blob/main/docs/recipes/docker-server/README.md Defines a Docker Compose setup for the LHCI server, specifying the image, port mapping, and a named volume for persistent data storage. ```yaml version: '3' services: lhserver: image: patrickhulce/lhci-server ports: - '9001:9001' volumes: - lhci-data:/data volumes: lhci-data: ```