New

Just launched: Vueblocks, a brand-new search engine for Vue packages! Explore Vueblocks →

jeffersongoncalves/laravel-page-cache

This Laravel package provides a full-page response cache middleware for stateless public GET pages. It caches 200 responses keyed by a version token, locale, and theme cookie, skips authenticated requests, exposes an X-Page-Cache HIT/MISS header, and offers a static flush() helper to invalidate every cached page at once.
1,055 1
Install
composer require jeffersongoncalves/laravel-page-cache
Latest Version:v1.3.0
PHP:^8.2
Laravel:11 · 12 · 13
License:MIT
Last Updated:Oct 25, 2026
Links: GitHub  ·  Packagist
Maintainer: jeffersongoncalves

Laravel Page Cache

Laravel Page Cache

Buy Me A Coffee

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

This Laravel package provides a full-page response cache middleware for stateless public GET pages. It caches 200 responses keyed by a version token, locale, and theme cookie, skips authenticated requests, exposes an X-Page-Cache HIT/MISS header, and offers a static flush() helper to invalidate every cached page at once.

Installation

You can install the package via composer:

composer require jeffersongoncalves/laravel-page-cache

You can publish the config file with:

php artisan vendor:publish --tag="laravel-page-cache-config"

This is the contents of the published config file:

return [
    'enabled' => env('PAGE_CACHE_ENABLED', true),

    // A TTL of 0 (or below) means "cache forever".
    'ttl' => (int) env('PAGE_CACHE_TTL', 3600),

    // Fold a normalized query string into the cache key (safe default).
    'include_query_string' => env('PAGE_CACHE_INCLUDE_QUERY_STRING', true),

    // Count hits/misses since the last flush (PageCache::stats()).
    'stats' => env('PAGE_CACHE_STATS', true),

    // Early path (ServeCachedPage): above 0 sends `Cache-Control: public, s-maxage=N` on its HITs.
    'early' => [
        's_maxage' => (int) env('PAGE_CACHE_EARLY_S_MAXAGE', 0),
    ],

    'key' => [
        'locale' => true,

        // Vary the cache on the negotiated content encoding.
        'accept_encoding' => true,

        'theme' => [
            'enabled' => true,
            'cookie' => 'theme',
        ],
    ],
];

Usage

Register CachePublicPage after StartSession and the authentication middleware — i.e. inside your web middleware group, not as the outermost middleware. The cache deliberately depends on a started session to tell guests from authenticated users, and registering it before StartSession would make it bail out on every request:

use Illuminate\Support\Facades\Route;
use JeffersonGoncalves\PageCache\Middleware\CachePublicPage;

Route::middleware(['web', CachePublicPage::class])->group(function () {
    Route::get('/', HomeController::class);
    Route::get('/{slug}', ShowController::class);
});

The first request to a path is computed normally and stored with an X-Page-Cache: MISS header. Subsequent requests are served straight from the cache with an X-Page-Cache: HIT header. Only stateless GET requests that return a 200 response from a guest (unauthenticated) visitor are cached, and the full response header bag (minus Set-Cookie) is replayed on a cache hit.

What is never cached (important)

To avoid leaking per-visitor state across visitors, the middleware passes the request through untouched (no read, no write) when any of the following is true:

  • the request is authenticated ($request->user() is not null);
  • there is no started session (so register it after StartSession);
  • the response sets its own cookies (Set-Cookie);
  • the response sends Cache-Control: no-store.

Cache-Control: no-store is the explicit opt-out you should reach for whenever a page renders per-visitor state. (Only no-store is honoured: Symfony stamps the default Cache-Control: no-cache, private on every response that does not set its own cache headers, so no-cache/private cannot be used as opt-out signals without disabling the cache for every page.)

Session/CSRF limitation — read this. Laravel flushes queued cookies (the session cookie, XSRF-TOKEN, flash data) into the response after this middleware has already inspected it, so the Set-Cookie guard above cannot see them. A page that embeds a @csrf token in a <form> therefore looks cacheable, and caching it would replay one visitor's CSRF token to everyone else. Any response that contains a CSRF token, a form, flash messages, or other guest-session content must mark itself with Cache-Control: no-store (e.g. return response($html)->header('Cache-Control', 'no-store');) or be kept out of the cached route group entirely. There is no reliable way for the middleware to detect this for you.

Serving HITs before the session starts (opt-in)

CachePublicPage runs after StartSession, so even a HIT starts a session (one session write per request with the database driver) and sends Set-Cookie for the session and XSRF-TOKEN, which keeps Cloudflare or any shared cache from caching the page. Prepend ServeCachedPage to the web group to answer those HITs before the session exists:

// bootstrap/app.php
use JeffersonGoncalves\PageCache\Middleware\ServeCachedPage;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(prepend: [ServeCachedPage::class]);
})

It only handles GET requests that carry no session cookie and no remember_* cookie and no Authorization header, so they are guests by definition and need no auth lookup. It computes the same key as CachePublicPage (PageCache::key()): on a HIT it returns the stored page with no session and no Set-Cookie; on a MISS, or for any request with a session or remember cookie, it falls through to the normal stack, where CachePublicPage stores the page as it does today. Set early.s_maxage (PAGE_CACHE_EARLY_S_MAXAGE) to send Cache-Control: public, s-maxage=N on these HITs so a CDN can cache them. A CDN keys on the URL alone, so only turn it on when the page does not vary by theme cookie or locale for the same URL.

Caveats:

  • CSRF. A page served this way has no session, so its CSRF token (<meta name="csrf-token">, Livewire's data-csrf) belongs to nobody. On interactive pages either limit the early path to crawlers (wrap or extend the middleware with e.g. jaybizzle/crawler-detect), or refresh the token on the client before the first form post or Livewire request.
  • Key inputs. The key is computed before StartSession, EncryptCookies and your route middleware. The locale must therefore already be known at that point (from the config or the URL, not from the session or a later middleware), or disable key.locale. The theme cookie must be excluded from encryption ($middleware->encryptCookies(except: ['theme'])), as a JavaScript-set theme cookie already has to be.
  • Route middleware is skipped on a HIT. The early path serves whatever CachePublicPage stored for the path without running the route's own middleware. If you put a cached route behind auth (or any other access check), call PageCache::forget() for it, or PageCache::flush(), when you deploy that change, or the page stored while it was public keeps being served until its TTL expires.
  • CDN freshness. With s_maxage set, PageCache::flush(), forget() and pause() only affect your application cache: the CDN keeps serving its copy until s-maxage expires. Purge the CDN when a change has to be visible immediately, or keep s_maxage short.

Invalidating the cache

Call CachePublicPage::flush() from your model observers to invalidate every cached page whenever the underlying content changes:

use JeffersonGoncalves\PageCache\Middleware\CachePublicPage;

class ProjectObserver
{
    public function saved(Project $project): void
    {
        CachePublicPage::flush();
    }

    public function deleted(Project $project): void
    {
        CachePublicPage::flush();
    }
}

flush() bumps an internal version token, so every previously cached page is bypassed on the next request without touching individual cache keys.

Runtime controls

JeffersonGoncalves\PageCache\PageCache keeps its state in the application cache, so it works without a deploy (and backs the Filament plugin):

use JeffersonGoncalves\PageCache\PageCache;

PageCache::flush();                    // every page (same as CachePublicPage::flush()); resets the counters
PageCache::forget('/pt_BR/projects');  // every variant of one path: locales, themes, encodings, query strings
PageCache::pause();                    // stop serving/storing cached pages...
PageCache::resume();                   // ...and start again
PageCache::stats();                    // ['enabled', 'paused', 'ttl', 'version', 'hits', 'misses', 'hit_ratio', 'flushed_at']

Hits and misses are counted since the last flush (one cache increment per cacheable request). Turn the counters off with 'stats' => false (PAGE_CACHE_STATS=false).

CSP nonces

If your pages carry a Content-Security-Policy nonce (Laravel's Vite::cspNonce(), used by @vite and Livewire), the cached entry keeps the nonce its markup was rendered with and hands it back to Vite on a HIT. A CSP header built afterwards — e.g. by laravel-security-headers 2.1+, registered outside this middleware — then matches the cached HTML instead of blocking its scripts. The nonce is shared by everyone who gets that cached page until it expires or is flushed.

Cache key

By default the cache key is composed of the version token, the current locale, the negotiated Accept-Encoding, the theme cookie value, a hash of the request path, and a hash of a normalized (sorted) query string. You can disable the locale, accept_encoding, or theme segments — or change the theme cookie name — through the config file. The Accept-Encoding segment is normalized (tokens lowercased and sorted) so a body compressed for a gzip/br client is never replayed to a client that cannot decode it.

The path (not the full URL) is used for the path segment, and the query string is normalized and hashed separately so that ?b=2&a=1 and ?a=1&b=2 collapse to the same entry while /products?page=2 stays distinct from /products?page=1. If a route ignores the query string entirely you can drop it from the key by setting include_query_string to false.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Related Packages

jeffersongoncalves/laravel-cookie-consent

This Laravel package provides a simple and elegant way to implement cookie conse...

18,107 5
jeffersongoncalves/laravel-gtm

This plugin seamlessly integrates Google Tag Manager (GTM) into your website, en...

6,920 4
jeffersongoncalves/laravel-cep

A simple and efficient PHP package for querying Brazilian postal codes (CEP). Th...

6,525 3
jeffersongoncalves/laravel-pwa-favicon

This Laravel package serves a spec-shaped PWA `manifest.json` (with Android dens...

5,222 3
jeffersongoncalves/laravel-favicon

This Laravel package serves a favicon.ico route, a browserconfig.xml for Windows...

4,205 2

Version History

Version Released PHP Laravel License
v1.3.0 ^8.2 ^11.0|^12.0|^13.0 MIT
v1.2.0 ^8.2 ^11.0|^12.0|^13.0 MIT
v1.1.1 ^8.2 ^11.0|^12.0|^13.0 MIT
v1.1.0 ^8.2 ^11.0|^12.0|^13.0 MIT
v1.0.1 ^8.2 ^11.0|^12.0|^13.0 MIT