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

Laravel Page Speed Laravel Package

vinkius-labs/laravel-page-speed

Laravel Page Speed adds a configurable optimization pipeline to Laravel apps, improving latency and bandwidth for Blade pages and API responses. Enable only the middleware you need; works with common cache drivers and supports Laravel 10–13.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**:
   ```bash
   composer require vinkius-labs/laravel-page-speed
   php artisan vendor:publish --provider="VinkiusLabs\LaravelPageSpeed\ServiceProvider"
  1. Enable for Web: Add middleware to bootstrap/app.php (Laravel 11+) or app/Http/Kernel.php (Laravel 10):
    // For Blade/HTML optimization
    $middleware->appendToGroup('web', [
        \VinkiusLabs\LaravelPageSpeed\Middleware\InlineCss::class,
        \VinkiusLabs\LaravelPageSpeed\Middleware\CollapseWhitespace::class,
    ]);
    
  2. Enable for APIs:
    // For API optimization
    $middleware->appendToGroup('api', [
        \VinkiusLabs\LaravelPageSpeed\Middleware\ApiResponseCache::class,
        \VinkiusLabs\LaravelPageSpeed\Middleware\ApiResponseCompression::class,
    ]);
    
  3. Configure (config/laravel-page-speed.php):
    'enable' => env('LARAVEL_PAGE_SPEED_ENABLE', true),
    'api_cache' => [
        'enabled' => env('API_CACHE_ENABLED', true),
        'driver' => env('API_CACHE_DRIVER', 'redis'),
        'ttl' => env('API_CACHE_TTL', 300),
    ],
    

First Use Case

Optimize a critical page:

  1. Add middleware to the web group.
  2. Test with:
    php artisan page-speed:test
    
  3. Verify improvements in Chrome DevTools' "Coverage" tab or Lighthouse audit.

Implementation Patterns

Workflow: Progressive Optimization

  1. Start with caching:

    // bootstrap/app.php
    $middleware->appendToGroup('api', [
        \VinkiusLabs\LaravelPageSpeed\Middleware\ApiResponseCache::class,
    ]);
    

    Configure dynamic tags for cache invalidation:

    'api_cache' => [
        'dynamic_tags' => true,
        'tag_derivation' => [
            'user/{id}' => ['user:{id}'],
            'posts' => ['posts:latest'],
        ],
    ],
    
  2. Add compression:

    $middleware->appendToGroup('api', [
        \VinkiusLabs\LaravelPageSpeed\Middleware\ApiResponseCompression::class,
    ]);
    

    Configure thresholds:

    'api_compression' => [
        'min_size' => 1024, // bytes
        'max_size' => 1048576, // 1MB
    ],
    
  3. Optimize HTML:

    $middleware->appendToGroup('web', [
        \VinkiusLabs\LaravelPageSpeed\Middleware\InlineCss::class,
        \VinkiusLabs\LaravelPageSpeed\Middleware\DeferJavascript::class,
    ]);
    

    Exclude specific routes:

    'web_optimization' => [
        'excluded_routes' => [
            'admin/*',
            'debugbar/*',
        ],
    ],
    

Integration Tips

  • Laravel Octane/Swoole: Reset middleware state in app/Providers/AppServiceProvider.php:
    public function boot(): void
    {
        if (app()->runningInConsole()) return;
        \VinkiusLabs\LaravelPageSpeed\PageSpeed::resetState();
    }
    
  • Dynamic Tag Derivation: Extend tag logic in app/Providers/PageSpeedServiceProvider.php:
    use VinkiusLabs\LaravelPageSpeed\Contracts\CacheTagDeriver;
    
    public function register(): void
    {
        $this->app->bind(CacheTagDeriver::class, function () {
            return new CustomTagDeriver();
        });
    }
    
  • Health Checks: Use the built-in /health endpoint for Kubernetes probes:
    Route::get('/health', \VinkiusLabs\LaravelPageSpeed\Middleware\ApiHealthCheck::class);
    

Gotchas and Tips

Pitfalls

  1. Middleware Order:

    • Place ApiResponseCache before ApiETag to avoid ETag generation on uncached responses.
    • Place InlineCss after ElideAttributes to prevent CSS inlining on removed elements.
  2. Persistent Environments (Octane/Swoole):

    • State Leak: Middleware like InlineCss uses static counters. Reset state in boot():
      \VinkiusLabs\LaravelPageSpeed\PageSpeed::resetState();
      
    • Cache Invalidation: Dynamic tags may accumulate in persistent processes. Use php artisan page-speed:clear-cache to reset.
  3. Content-Type Guard:

    • Middleware skips non-HTML responses (e.g., JSON). For custom content types, override:
      \VinkiusLabs\LaravelPageSpeed\PageSpeed::setContentTypeGuard(function ($contentType) {
          return !in_array($contentType, ['text/html', 'application/xhtml+xml']);
      });
      
  4. Livewire/Alpine Attributes:

    • CollapseWhitespace preserves wire:, x-, and data-* attributes by default. To customize:
      'whitespace_preservation' => [
          'attributes' => ['wire:', 'x-', 'data-*', 'custom-attr'],
      ],
      

Debugging

  1. Performance Headers:

    • Check X-Response-Time, X-Memory-Usage, and X-Cache-Status in responses. Example:
      X-Cache-Status: HIT (TTL: 240s)
      X-Response-Time: 12ms
      
    • High X-Memory-Usage may indicate regex exhaustion (see #217).
  2. Circuit Breaker:

    • If X-Circuit-Breaker-State: OPEN, check:
      • API_CIRCUIT_BREAKER_THRESHOLD (default: 5 failures).
      • API_CIRCUIT_BREAKER_TIMEOUT (default: 60s).
    • Reset manually:
      php artisan page-speed:reset-circuit-breaker
      
  3. Cache Issues:

    • Verify API_CACHE_DRIVER matches your CACHE_DRIVER (e.g., redis).
    • Dynamic tags may cause cache misses. Test with:
      php artisan page-speed:debug-cache
      

Extension Points

  1. Custom Middleware: Extend VinkiusLabs\LaravelPageSpeed\PageSpeed:

    namespace App\Middleware;
    
    use VinkiusLabs\LaravelPageSpeed\PageSpeed;
    
    class CustomOptimizer extends PageSpeed
    {
        public function apply($content): string
        {
            // Custom logic
            return parent::apply($content);
        }
    }
    
  2. Tag Derivation: Implement CacheTagDeriver:

    use VinkiusLabs\LaravelPageSpeed\Contracts\CacheTagDeriver;
    
    class CustomTagDeriver implements CacheTagDeriver
    {
        public function deriveTags(string $path): array
        {
            return ['custom:tag'];
        }
    }
    
  3. Compression Strategies: Override ApiResponseCompression:

    protected function getCompressionAlgorithm(): string
    {
        return 'zstd'; // Use Zstandard instead of Brotli
    }
    

Configuration Quirks

  • API_CACHE_DYNAMIC_TAGS: Set to false for static APIs (e.g., documentation). Dynamic tags add overhead (~1-2ms per request).
  • INLINE_CSS_MAX_SIZE: Default: 10KB. Increase for complex stylesheets to avoid performance cliffs.
  • DEFER_JS_EXCLUDE_PATTERNS: Exclude critical scripts:
    'defer_javascript' => [
        'exclude_patterns' => [
            'https://cdn.example.com/critical.js',
            '*.analytics.js',
        ],
    ],
    

Pro Tips

  1. A/B Testing: Use LARAVEL_PAGE_SPEED_ENABLE=false in a cookie-based flag to compare optimized vs. non-optimized paths.
  2. Edge Caching: Configure CDN to cache responses with X-Cache-Status: HIT headers.
  3. Monitoring: Export X-Performance-Warning headers to your APM (e.g., Datadog) to track slow queries or large payloads.
  4. **Local Testing
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi