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

Optimize Laravel HTML and API responses with a configurable middleware pipeline: minify HTML/JSON/XML, add cache headers, ETags, compression and more. Works across Laravel 10–13 with any cache store (Redis, Memcached, file, etc.) for faster, leaner responses.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require vinkius-labs/laravel-page-speed
    php artisan vendor:publish --provider="VinkiusLabs\LaravelPageSpeed\ServiceProvider"
    

    Publish the config file to config/laravel-page-speed.php.

  2. Enable for Web (Blade) Add middleware to bootstrap/app.php (Laravel 11+) or app/Http/Kernel.php (Laravel 10):

    // For Laravel 11+ (bootstrap/app.php)
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->appendToGroup('web', [
            \VinkiusLabs\LaravelPageSpeed\Middleware\InlineCss::class,
            \VinkiusLabs\LaravelPageSpeed\Middleware\CollapseWhitespace::class,
        ]);
    });
    
  3. Enable for APIs (JSON/XML) Add API middleware to the same file:

    $middleware->appendToGroup('api', [
        \VinkiusLabs\LaravelPageSpeed\Middleware\ApiResponseCache::class,
        \VinkiusLabs\LaravelPageSpeed\Middleware\ApiResponseCompression::class,
    ]);
    
  4. Configure Environment Add to .env:

    LARAVEL_PAGE_SPEED_ENABLE=true
    API_CACHE_ENABLED=true
    API_CACHE_DRIVER=redis
    API_CACHE_TTL=300
    
  5. First Use Case Test a Blade page or API endpoint. Verify optimizations via:

    • Web: Inspect HTML source (minified, critical CSS inlined).
    • API: Check X-Cache-Status header (e.g., HIT or MISS).

Implementation Patterns

Workflow: Optimizing a Blade Page

  1. Select Middleware Start with core optimizations:

    // bootstrap/app.php
    $middleware->appendToGroup('web', [
        \VinkiusLabs\LaravelPageSpeed\Middleware\InlineCss::class,          // Critical CSS
        \VinkiusLabs\LaravelPageSpeed\Middleware\ElideAttributes::class,     // Remove redundant attributes
        \VinkiusLabs\LaravelPageSpeed\Middleware\CollapseWhitespace::class,  // Minify HTML
        \VinkiusLabs\LaravelPageSpeed\Middleware\DeferJavascript::class,    // Defer non-critical JS
    ]);
    
  2. Exclude Routes Skip optimizations for admin or debug routes in config/laravel-page-speed.php:

    'skip' => [
        'admin/*',
        'telescope/*',
        'horizon/*',
    ],
    
  3. Monitor Impact Use HTTP headers (X-Response-Time, X-Cache-Status) or tools like Lighthouse to measure improvements.


Workflow: Caching API Responses

  1. Configure Cache

    API_CACHE_ENABLED=true
    API_CACHE_DRIVER=redis
    API_CACHE_TTL=600  # 10-minute cache
    API_CACHE_DYNAMIC_TAGS=true  # Auto-generate tags from route
    
  2. Tag-Based Invalidation Manually invalidate cache for specific routes:

    use VinkiusLabs\LaravelPageSpeed\Facades\PageSpeed;
    
    PageSpeed::invalidateCache('products/{id}', ['product:123']);
    
  3. Fallback Logic Use ApiCircuitBreaker for resilience:

    // config/laravel-page-speed.php
    'circuit_breaker' => [
        'enabled' => true,
        'threshold' => 5,  // Fail 5 requests in 10s to trip
        'timeout' => 60,   // Reset after 60s
    ],
    

Integration Tips

  • Livewire/Alpine.js Compatibility Preserve dynamic attributes by adding to config/laravel-page-speed.php:

    'preserve_attributes' => [
        'wire:*', 'x-*', 'x-data', 'x-init',
    ],
    
  • API Versioning Exclude /v1/ from caching if using versioned APIs:

    'skip' => [
        'api/v1/*',
    ],
    
  • Health Checks Add ApiHealthCheck middleware to api group for Kubernetes probes:

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

Gotchas and Tips

Pitfalls

  1. Middleware Order Matters

    • Issue: InlineCss must run before CollapseWhitespace to avoid minifying inlined CSS.
    • Fix: Order middleware in Kernel.php or app.php accordingly.
  2. Cache Driver Mismatch

    • Issue: ApiCircuitBreaker uses the default cache driver unless configured otherwise (fixed in v4.4.3).
    • Fix: Set API_CACHE_DRIVER in .env to match your circuit breaker’s needs.
  3. Dynamic Content Corruption

    • Issue: ElideAttributes or TrimUrls may break JavaScript strings or SVG tags.
    • Fix: Exclude problematic attributes in config:
      'elide_attributes' => [
          'exclude' => ['data-js-string', 'xmlns'],
      ],
      
  4. Livewire/Alpine.js Attributes

    • Issue: CollapseWhitespace may corrupt wire:* or x-* attributes.
    • Fix: Add to preserve_attributes in config:
      'preserve_attributes' => ['wire:*', 'x-*'],
      
  5. Debugbar/Telescope Conflicts

    • Issue: Optimizations may interfere with debug tools.
    • Fix: Skip debug routes in config/laravel-page-speed.php:
      'skip' => ['_debugbar', 'telescope', 'horizon'],
      

Debugging

  1. Check Headers Use curl -I or browser dev tools to inspect:

    • X-Cache-Status: HIT/MISS/BYPASS.
    • X-Performance-Warning: Triggers for slow queries or high latency.
  2. Log Middleware Execution Enable debug mode in .env:

    LARAVEL_PAGE_SPEED_DEBUG=true
    

    Logs will appear in storage/logs/laravel-page-speed.log.

  3. Test Locally Use php artisan page-speed:test to validate middleware behavior without affecting production.


Extension Points

  1. Custom Middleware Extend the base PageSpeed class to add logic:

    use VinkiusLabs\LaravelPageSpeed\PageSpeed;
    
    class CustomOptimizer extends PageSpeed {
        protected function apply($content) {
            // Custom logic here
            return parent::apply($content);
        }
    }
    
  2. Override Config Publish and modify config/laravel-page-speed.php:

    php artisan vendor:publish --tag="laravel-page-speed-config"
    
  3. Dynamic Tag Generation Customize cache tags for APIs:

    // In a controller or service
    use VinkiusLabs\LaravelPageSpeed\Facades\PageSpeed;
    
    PageSpeed::setDynamicTags(['user:{id}', 'role:{role}']);
    
  4. Circuit Breaker Fallbacks Define fallback responses in config:

    'circuit_breaker' => [
        'fallback' => [
            'status' => 503,
            'content' => 'Service Unavailable',
        ],
    ],
    

Pro Tips

  • A/B Testing Use LARAVEL_PAGE_SPEED_ENABLE=false in .env for control groups.

  • Bandwidth Savings Combine with ApiResponseCompression (Brotli/Gzip) for APIs:

    API_COMPRESSION_ENABLED=true
    API_COMPRESSION_THRESHOLD=1024  # Compress responses >1KB
    
  • Monitor Cache Hit Rate Track X-Cache-Status: HIT in your APM (e.g., Datadog, New Relic).

  • Exclude Large Payloads Skip optimizations for binary responses (e.g., PDFs):

    'skip_content_types' => [
        'application/pdf',
        'image/*',
    ],
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui