Jump24 - Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

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
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
Tinkerwell logo

Tinkerwell

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

Tinkerwell
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
PhpStorm logo

PhpStorm

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

PhpStorm
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
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

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

Shift
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
Lucky Media logo

Lucky Media

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

Lucky Media
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

The latest

View all →
Inertia.js v3.0.0 Is Here with Optimistic Updates, useHttp, and More image

Inertia.js v3.0.0 Is Here with Optimistic Updates, useHttp, and More

Read article
Laravel Boost v2.4.0 Adds Security Audits and a Laravel Best Practices Skill image

Laravel Boost v2.4.0 Adds Security Audits and a Laravel Best Practices Skill

Read article
Building Transaction-Safe Multi-Document Operations in Laravel image

Building Transaction-Safe Multi-Document Operations in Laravel

Read article
Ship AI with Laravel: Building Your First Agent with Laravel 13's AI SDK image

Ship AI with Laravel: Building Your First Agent with Laravel 13's AI SDK

Read article
OG Kit: Generate Dynamic Open Graph Images with HTML and CSS image

OG Kit: Generate Dynamic Open Graph Images with HTML and CSS

Read article
Prism Workers AI — A Cloudflare Workers AI Provider for Prism PHP image

Prism Workers AI — A Cloudflare Workers AI Provider for Prism PHP

Read article