Caching Laravel HTML With Cloudflare

under Laravel

If you're serving any sort of content site with Laravel, you've probably looked into setting up caching for your page responses. For this site owenconti.com, I'm letting Cloudflare handle the caching for me. I do this by setting up a Page Rule to "cache everything":

Cloudflare page rule to cache everything

The above page rule will cache everything that the Laravel app returns. However, Cloudflare does not cache responses that modify cookies. By default, Laravel's web middleware is setup to handle sessions for you.

Removing Session Middleware

Since this site is purely for anonymous visitors, I'll never need to use sessions or cookies of any sort. Because of that, I am able to remove all of the session and cookie middlewares from the web middleware group:

1// app\Http\Kernel.php
2 
3<?php
4 
5namespace App\Http;
6 
7use Illuminate\Foundation\Http\Kernel as HttpKernel;
8 
9class Kernel extends HttpKernel
10{
11 protected $middleware = [
12 // ...
13 ];
14 
15 /**
16 * The application's route middleware groups.
17 *
18 * @var array
19 */
20 protected $middlewareGroups = [
21 'web' => [
22 \App\Http\Middleware\EncryptCookies::class,
23 \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
24 \Illuminate\Session\Middleware\StartSession::class,
25 \Illuminate\Session\Middleware\AuthenticateSession::class,
26 \Illuminate\View\Middleware\ShareErrorsFromSession::class,
27 \App\Http\Middleware\VerifyCsrfToken::class,
28 \Illuminate\Routing\Middleware\SubstituteBindings::class,
29 ],
30 
31 'api' => [
32 'throttle:api',
33 \Illuminate\Routing\Middleware\SubstituteBindings::class,
34 ],
35 ];

After removing the session and cookie middlewares, Cloudflare will start to properly cache HTML responses from the Laravel application.

You can validate this by checking the response headers of the HTML response:

1cache-control: public, max-age=3600, s-maxage=86400
2cf-cache-status: HIT
3cf-ray: 6803f1964956e472-SEA

Thanks for reading this article!

Hopefully you found this article useful! If you did, share it on Twitter!

Found an issue with the article? Submit your edits against the repository.