Certainly! Here's a solution tailored to your scenario with Laravel and CDN caching:
Why This Happens
By default, Laravel's web routes (using the web middleware group) are stateful sessions, CSRF protection, etc., which sets cookies (<appname>_session and XSRF-TOKEN) and applies private/no-cache headers for user security.
Implications
- Session cookies: Mark requests as user-specific (dynamic), so CDNs/proxies won't cache the pages.
- Cache-Control: private, no-cache...: Instructs intermediate caches (like Varnish and Cloudflare) not to cache these responses.
When Should You Change This?
- For logged-in/personalized pages: Keep current settings; don't cache.
- For public pages (e.g., marketing pages, docs): You can safely remove session cookies and change cache headers to enable CDN/proxy caching.
How To Adjust Cache Headers & Cookies
1. Exclude Session/Cookie Middleware for Public Pages
Move public routes into a new middleware group that doesn’t start a session or set CSRF cookies:
// In routes/web.php
Route::middleware(['public.cache'])->group(function () {
Route::get('/', [LandingPageController::class, 'show']);
// ...other non-personalized routes
});
Then in app/Http/Kernel.php, add:
protected $middlewareGroups = [
//...
'public.cache' => [
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
// don't include StartSession or VerifyCsrfToken
],
];
2. Manually Set Cache Headers on Responses
For those routes, set more permissive headers in the controller:
public function show(Request $request)
{
return response(view('homepage'))
->header('Cache-Control', 'public, max-age=3600, s-maxage=3600');
}
3. Remove XSRF-TOKEN Cookie
- Only generated by Laravel's VerifyCsrfToken middleware (part of web group).
- Not included if you remove that middleware for public pages.
4. Cloudflare Caching
- In Cloudflare, set a page rule to respect origin cache headers.
- Optionally, you can force "Cache Everything".
5. Varnish
- Ensure Varnish is configured to pass or cache correctly by looking at cookies and cache headers.
6. Testing
curl -I https://yourdomain.comand confirmCache-Controlis set as you wish and no cookies are present for your public pages.
Summary
Yes, it's default for web routes. To enable cache/CDN optimizations:
- Separate out public/static routes to not use session/csrf/cookie middleware.
- Set custom cache headers for those routes.
Let me know if you want example code for a custom middleware to handle this as well!