Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Lighthouse Php Laravel Package

spatie/lighthouse-php

Run Google Lighthouse audits from PHP. Test any URL and retrieve category scores (performance, accessibility, SEO, etc.) and individual audit details. Configure headers, user agent, categories, CPU throttling, and max load wait, then run and parse results.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require spatie/lighthouse-php
    

    Ensure your Laravel project has PHP 8.1+ and Chrome/Chromium installed (required for headless execution).

  2. First Use Case Run a basic audit on a URL:

    use Spatie\Lighthouse\Lighthouse;
    
    $result = Lighthouse::url('https://example.com')->run();
    $result->performanceScore; // Access individual scores
    
    • Key Outputs: $result contains scores (performance, accessibility, etc.), audits, and error details.
  3. Where to Look First

    • Documentation: Covers configuration, customization, and advanced usage.
    • LighthouseResult Class: Inspect the returned object’s methods (e.g., getAudits(), getErrors()).
    • .env Configuration: Check for LIGHTHOUSE_CHROMIUM_PATH if using a custom Chromium binary.

Implementation Patterns

Core Workflows

  1. Running Audits

    • URL Audits:
      $result = Lighthouse::url('https://example.com')->run();
      
    • HTML String Audits (for dynamic content):
      $result = Lighthouse::html($htmlString)->run();
      
    • Local File Audits (for offline testing):
      $result = Lighthouse::file('/path/to/index.html')->run();
      
  2. Configuration

    • Custom Chromium Path:
      config(['lighthouse.chromium_path' => '/custom/path/to/chromium']);
      
    • Throttling (Simulate Network Conditions):
      $result = Lighthouse::url('https://example.com')
          ->withThrottling(3G()) // Use predefined presets (e.g., 3G(), DSL(), etc.)
          ->run();
      
    • Custom Port (for CI/CD environments):
      $result = Lighthouse::url('https://example.com')
          ->withPort(9222) // Debugging port
          ->run();
      
  3. Integration with Laravel

    • Artisan Command (for CLI access):
      php artisan lighthouse:run --url=https://example.com
      
      Register the command in app/Console/Kernel.php:
      protected $commands = [
          \Spatie\Lighthouse\Console\RunLighthouse::class,
      ];
      
    • Scheduled Audits (via Laravel Scheduler):
      // app/Console/Kernel.php
      protected function schedule(Schedule $schedule)
      {
          $schedule->command('lighthouse:run --url=https://example.com')
              ->daily();
      }
      
    • Queue Jobs (for async processing):
      use Spatie\Lighthouse\Jobs\RunLighthouseJob;
      
      RunLighthouseJob::dispatch('https://example.com')
          ->onQueue('lighthouse');
      
  4. Handling Results

    • Access Scores:
      $performanceScore = $result->performanceScore;
      $accessibilityScore = $result->accessibilityScore;
      
    • Iterate Over Audits:
      foreach ($result->audits as $audit) {
          if ($audit->score < 0.9) {
              // Log or notify about failing audits
          }
      }
      
    • Store Results in Database:
      $result->toArray(); // Convert to array for storage
      
  5. Customizing Lighthouse Flags

    • Pass additional flags to Chromium:
      $result = Lighthouse::url('https://example.com')
          ->withFlags(['--headless=new', '--disable-gpu'])
          ->run();
      

Gotchas and Tips

Pitfalls

  1. Chromium Dependencies

    • Error: Failed to start Chromium or Chromium not found.
      • Fix: Ensure Chromium is installed and the path is correct in .env:
        LIGHTHOUSE_CHROMIUM_PATH=/usr/bin/chromium-browser
        
      • Docker Tip: Use the official spatie/lighthouse-php Docker image to avoid setup hassles.
  2. Performance Issues

    • Error: Audits time out or fail due to slow network/large pages.
      • Fix:
        • Increase timeout:
          $result = Lighthouse::url('https://example.com')
              ->withTimeout(120) // Default: 30 seconds
              ->run();
          
        • Use throttling to simulate slower connections (e.g., 3G()).
  3. Dynamic Content

    • Issue: SPAs or JavaScript-rendered content may not load correctly in headless mode.
      • Fix:
        • Use withViewport() to mimic mobile/desktop:
          $result = Lighthouse::url('https://example.com')
              ->withViewport(1920, 1080) // Desktop
              ->run();
          
        • Add delays for async content:
          $result = Lighthouse::url('https://example.com')
              ->withEmulation(['timezone' => 'America/New_York', 'latitude' => 37.7749, 'longitude' => -122.4194])
              ->run();
          
  4. CI/CD Environments

    • Issue: Chromium may not be available in CI (e.g., GitHub Actions).
      • Fix:
        • Use a pre-installed Chromium image (e.g., cypress/included:12.0.0 in Docker).
        • Cache Chromium between runs to speed up CI:
          # .github/workflows/lighthouse.yml
          steps:
            - uses: actions/cache@v3
              with:
                path: ~/.cache/chromium
                key: ${{ runner.os }}-chromium
          
  5. Memory Limits

    • Error: Out of memory for large pages.
      • Fix:
        • Increase PHP memory limit in .env:
          MEMORY_LIMIT=4G
          
        • Run audits on smaller subsets of content or use --headless=new (more memory-efficient).
  6. Authentication

    • Issue: Protected routes (e.g., admin dashboards) fail without credentials.
      • Fix:
        • Use withCookies() or withLocalStorage() to inject auth tokens:
          $result = Lighthouse::url('https://example.com/dashboard')
              ->withCookies(['auth_token' => 'abc123'])
              ->run();
          
        • For Laravel, use laravel-shift/dump-server to capture authenticated sessions.

Debugging Tips

  1. Verbose Output Enable debug logs to see Chromium output:

    $result = Lighthouse::url('https://example.com')
        ->withDebug(true)
        ->run();
    

    Check logs in storage/logs/lighthouse.log.

  2. Inspect Chromium Process Run Lighthouse with a debugging port:

    $result = Lighthouse::url('https://example.com')
        ->withPort(9222)
        ->run();
    

    Then connect via Chrome DevTools to http://localhost:9222.

  3. Validate HTML Ensure the HTML/URL is valid before running audits:

    if (!$result->isSuccessful()) {
        foreach ($result->errors as $error) {
            Log::error($error);
        }
    }
    

Extension Points

  1. Custom Audits Extend Lighthouse with additional flags or scripts:

    $result = Lighthouse::url('https://example.com')
        ->withCustomFlags(['--run-script=customScript'])
        ->run();
    
  2. Post-Processing Transform results before storage:

    $processed = $result->toArray();
    $processed['final_score'] = ($processed['performanceScore'] + $processed['accessibilityScore']) / 2;
    
  3. Webhook Notifications Trigger alerts for failing audits:

    if ($result->performanceScore < 0.9) {
        Http::post('https://your-webhook-url', [
            'score' => $result->performanceScore,
            'url' => 'https://example.com',
        ]);
    }
    
  4. Parallel Audits Use Laravel Queues to run multiple audits concurrently:

    foreach ($urls as $url) {
        RunLighthouseJob::dispatch($url)->onQueue('lighthouse');
    }
    
  5. Integration with Monitoring Sync results with tools like Datadog, Sentry, or custom dashboards:

    // Example: Log to Sentry
    if ($result->hasErrors()) {
        Sentry
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport