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.
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.
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,
]);
});
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,
]);
Configure Environment
Add to .env:
LARAVEL_PAGE_SPEED_ENABLE=true
API_CACHE_ENABLED=true
API_CACHE_DRIVER=redis
API_CACHE_TTL=300
First Use Case Test a Blade page or API endpoint. Verify optimizations via:
X-Cache-Status header (e.g., HIT or MISS).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
]);
Exclude Routes
Skip optimizations for admin or debug routes in config/laravel-page-speed.php:
'skip' => [
'admin/*',
'telescope/*',
'horizon/*',
],
Monitor Impact
Use HTTP headers (X-Response-Time, X-Cache-Status) or tools like Lighthouse to measure improvements.
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
Tag-Based Invalidation Manually invalidate cache for specific routes:
use VinkiusLabs\LaravelPageSpeed\Facades\PageSpeed;
PageSpeed::invalidateCache('products/{id}', ['product:123']);
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
],
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,
]);
Middleware Order Matters
InlineCss must run before CollapseWhitespace to avoid minifying inlined CSS.Kernel.php or app.php accordingly.Cache Driver Mismatch
ApiCircuitBreaker uses the default cache driver unless configured otherwise (fixed in v4.4.3).API_CACHE_DRIVER in .env to match your circuit breaker’s needs.Dynamic Content Corruption
ElideAttributes or TrimUrls may break JavaScript strings or SVG tags.'elide_attributes' => [
'exclude' => ['data-js-string', 'xmlns'],
],
Livewire/Alpine.js Attributes
CollapseWhitespace may corrupt wire:* or x-* attributes.preserve_attributes in config:
'preserve_attributes' => ['wire:*', 'x-*'],
Debugbar/Telescope Conflicts
config/laravel-page-speed.php:
'skip' => ['_debugbar', 'telescope', 'horizon'],
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.Log Middleware Execution
Enable debug mode in .env:
LARAVEL_PAGE_SPEED_DEBUG=true
Logs will appear in storage/logs/laravel-page-speed.log.
Test Locally
Use php artisan page-speed:test to validate middleware behavior without affecting production.
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);
}
}
Override Config
Publish and modify config/laravel-page-speed.php:
php artisan vendor:publish --tag="laravel-page-speed-config"
Dynamic Tag Generation Customize cache tags for APIs:
// In a controller or service
use VinkiusLabs\LaravelPageSpeed\Facades\PageSpeed;
PageSpeed::setDynamicTags(['user:{id}', 'role:{role}']);
Circuit Breaker Fallbacks Define fallback responses in config:
'circuit_breaker' => [
'fallback' => [
'status' => 503,
'content' => 'Service Unavailable',
],
],
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/*',
],
How can I help you explore Laravel packages today?