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.
Installation
composer require spatie/lighthouse-php
Ensure your Laravel project has PHP 8.1+ and Chrome/Chromium installed (required for headless execution).
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
$result contains scores (performance, accessibility, etc.), audits, and error details.Where to Look First
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.Running Audits
$result = Lighthouse::url('https://example.com')->run();
$result = Lighthouse::html($htmlString)->run();
$result = Lighthouse::file('/path/to/index.html')->run();
Configuration
config(['lighthouse.chromium_path' => '/custom/path/to/chromium']);
$result = Lighthouse::url('https://example.com')
->withThrottling(3G()) // Use predefined presets (e.g., 3G(), DSL(), etc.)
->run();
$result = Lighthouse::url('https://example.com')
->withPort(9222) // Debugging port
->run();
Integration with Laravel
php artisan lighthouse:run --url=https://example.com
Register the command in app/Console/Kernel.php:
protected $commands = [
\Spatie\Lighthouse\Console\RunLighthouse::class,
];
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
$schedule->command('lighthouse:run --url=https://example.com')
->daily();
}
use Spatie\Lighthouse\Jobs\RunLighthouseJob;
RunLighthouseJob::dispatch('https://example.com')
->onQueue('lighthouse');
Handling Results
$performanceScore = $result->performanceScore;
$accessibilityScore = $result->accessibilityScore;
foreach ($result->audits as $audit) {
if ($audit->score < 0.9) {
// Log or notify about failing audits
}
}
$result->toArray(); // Convert to array for storage
Customizing Lighthouse Flags
$result = Lighthouse::url('https://example.com')
->withFlags(['--headless=new', '--disable-gpu'])
->run();
Chromium Dependencies
Failed to start Chromium or Chromium not found.
.env:
LIGHTHOUSE_CHROMIUM_PATH=/usr/bin/chromium-browser
spatie/lighthouse-php Docker image to avoid setup hassles.Performance Issues
$result = Lighthouse::url('https://example.com')
->withTimeout(120) // Default: 30 seconds
->run();
3G()).Dynamic Content
withViewport() to mimic mobile/desktop:
$result = Lighthouse::url('https://example.com')
->withViewport(1920, 1080) // Desktop
->run();
$result = Lighthouse::url('https://example.com')
->withEmulation(['timezone' => 'America/New_York', 'latitude' => 37.7749, 'longitude' => -122.4194])
->run();
CI/CD Environments
cypress/included:12.0.0 in Docker).# .github/workflows/lighthouse.yml
steps:
- uses: actions/cache@v3
with:
path: ~/.cache/chromium
key: ${{ runner.os }}-chromium
Memory Limits
Out of memory for large pages.
.env:
MEMORY_LIMIT=4G
--headless=new (more memory-efficient).Authentication
withCookies() or withLocalStorage() to inject auth tokens:
$result = Lighthouse::url('https://example.com/dashboard')
->withCookies(['auth_token' => 'abc123'])
->run();
laravel-shift/dump-server to capture authenticated sessions.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.
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.
Validate HTML Ensure the HTML/URL is valid before running audits:
if (!$result->isSuccessful()) {
foreach ($result->errors as $error) {
Log::error($error);
}
}
Custom Audits Extend Lighthouse with additional flags or scripts:
$result = Lighthouse::url('https://example.com')
->withCustomFlags(['--run-script=customScript'])
->run();
Post-Processing Transform results before storage:
$processed = $result->toArray();
$processed['final_score'] = ($processed['performanceScore'] + $processed['accessibilityScore']) / 2;
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',
]);
}
Parallel Audits Use Laravel Queues to run multiple audits concurrently:
foreach ($urls as $url) {
RunLighthouseJob::dispatch($url)->onQueue('lighthouse');
}
Integration with Monitoring Sync results with tools like Datadog, Sentry, or custom dashboards:
// Example: Log to Sentry
if ($result->hasErrors()) {
Sentry
How can I help you explore Laravel packages today?