Avoid showing user specific information by wrongful caching in Varnish Cache
Usually guests see some bits different then logged in users. A simple way to start with Varnish is to avoid all the caching logic for logged in users.
There are other ways to achieve high caching hit rate, also in combination with logged in users. But for starters it is sufficient to start with just skipping all the cache specific business logic in Varnish and pass logged in users right through to the application.
We need an indicator
Somehow we need to know how to differentiate between a logged in users and guests. And most of the time this is done using cookies.
If a user does not send a cookie like "loggedin" with each request, we can assume that this is a guest. Some CMS or applications do it out of the box. For example: TYPO3 sets a "be_user" for logged in backend users, or "fe_user" for logged in frontend users.
In Varnish you could handle that case like this:
sub vcl_recv {
if (req.http.Cookie ~ "(?i)(loggedin|be_user|fe_user)") {
return (pass);
}
}
But then there are application frameworks like Laravel which do nothing of the kind. Here we need to put in some little extra work. The way to go is: on login, or even better, as a middleware on each request: check if a user is logged in, and if he is, set a cookie indicating the he is logged in, with the exact duration of his session. Something like this:
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
class AddAuthStatus
{
public function handle(Request $request, \Closure $next)
{
/** @var \Illuminate\Http\Response $response */
$response = $next($request);
if (\Auth::guard()->check() && method_exists($response, 'cookie')) {
$response->cookie('loggedin', 1, config('session.lifetime'));
}
return $response;
}
}
And finally you add this middleware to your Kernel:
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middlewareGroups = [
'web' => [
// ...
\App\Http\Middleware\AddAuthStatus::class,
],
];
}