Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

Separate your Cloudflare page cache with a middleware group

Last updated on by

Separate your Cloudflare page cache with a middleware group image

Over the last few months I have taken laravelshift.com from 6% cached to 98% cached. When I first started this journey, I remember searching for caching a Laravel app with Cloudflare. The top two results were a post by Andy Hinkle and a package.

Both used middleware to set cache headers for Cloudflare. Unfortunately, both had drawbacks. While they do set the appropriate header, Cloudflare would bypass Andy's solution. This is because the response also included Set-Cookie headers (default Laravel behavior). The package would completely remove the Set-Cookie header. Which is very dangerous. As you could cache a version of the page with user specific data.

I wanted something more intentional. More explicit. That way I could avoid any gotchas while caching pages. Instead, I decided to register a new static middleware group.

// bootstrap/app.php
->withRouting(
web: __DIR__ . '/../routes/web.php',
api: __DIR__ . '/../routes/api.php',
commands: __DIR__ . '/../routes/console.php',
channels: __DIR__ . '/../routes/channels.php',
then: function () {
Route::middleware('static')
->group(base_path('routes/static.php'));
}
)

This group is effectively a copy of the api middleware group. It removes all the stateful web middleware, such as starting the session or encrypting cookies. All it does is set the cache headers and allow for route parameter bindings.

$middleware->group('static', [
\App\Http\Middleware\SetCacheControlHeader::class
\Illuminate\Routing\Middleware\SubstituteBindings::class,
]);

By removing all the stateful middleware, I prevent inadvertently using stateful data on a cacheable page. Either from the session or a cookie. The middleware group also allows me to explicitly define cacheable pages in a separate route file. Now I register any static pages in a routes/static.php, This makes it really easy to list pages that are cached.

For example, using:

php artisan route:list --middleware=static

Using a separate middleware group is a straightforward way to cache pages with Cloudflare (or any cache). It avoids common side-effects and explicitly separates your cacheable pages. If you're interested in making your Laravel apps respond crazy fast, check out my Fast Laravel video course.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review
Laravel Cloud logo

Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Cloud
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
SerpApi logo

SerpApi

Access real-time search engine results through a simple API—no more scraping headaches! Use it for AI applications, SEO tools, product research, travel information, and more

SerpApi
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media

The latest

View all →
Generate Livewire Skeleton Placeholders Automatically with Wirebones image

Generate Livewire Skeleton Placeholders Automatically with Wirebones

Read article
Laravel ClickHouse: A Full-Featured ClickHouse Driver for Laravel image

Laravel ClickHouse: A Full-Featured ClickHouse Driver for Laravel

Read article
Laravel Installer Now Returns JSON When Running Inside an AI Agent image

Laravel Installer Now Returns JSON When Running Inside an AI Agent

Read article
Queue-Wide Inspection Methods in Laravel 13.8.0 image

Queue-Wide Inspection Methods in Laravel 13.8.0

Read article
Verifiable Audit Logging with Laravel Chronicle image

Verifiable Audit Logging with Laravel Chronicle

Read article
Ship AI with Laravel: Search Entire PDFs with Zero Search Logic image

Ship AI with Laravel: Search Entire PDFs with Zero Search Logic

Read article