4,000 emails/month for free | Mailtrap sends real emails 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
Tinkerwell

Enjoy coding and debugging in an editor designed for fast feedback and quick iterations. It's like a shell for your application – but with multi-line editing, code completion, and more.

Visit Tinkerwell
Curotec logo

Curotec

World class Laravel experts with GenAI dev skills. LATAM-based, embedded engineers that ship fast, communicate clearly, and elevate your product. No bloat, no BS.

Curotec
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
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
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 →
Migrating Laravel News from Laravel Forge to Cloud image

Migrating Laravel News from Laravel Forge to Cloud

Read article
Laravel News Is the Live Stream Partner for Laracon EU 2026 image

Laravel News Is the Live Stream Partner for Laracon EU 2026

Read article
Query Builder Expression Aliases in Laravel 12.48 image

Query Builder Expression Aliases in Laravel 12.48

Read article
Restrict User Actions with Time-Based Sanctions Using Laravel Prohibitions image

Restrict User Actions with Time-Based Sanctions Using Laravel Prohibitions

Read article
Laravel Invite Only Adds a Full User Invitation System with Tokens, Events, and Reminders image

Laravel Invite Only Adds a Full User Invitation System with Tokens, Events, and Reminders

Read article
Docker Support in Laravel VS Code Extension v1.4.2 image

Docker Support in Laravel VS Code Extension v1.4.2

Read article