[How2Tips] How to force the refresh of a page after after hitting the back button?

Published on

Oct 17, 2017

how2tips

Most of the time the browser will display the previous page from the cache without making a request to the server. Actually it's not a problem except in the case where the user has just completed a complicated multi-page wizard or checkout process and then hits the back button. In order to prevent the user to load a previous page state, the solution is to add specific `Cache-Control` headers to the targeted pages:

Cache-Control: no-cache, max-age=0, must-revalidate, no-store

For example with Symfony, you can select specific routes and apply the desired headers thanks to the event kernel.response.

namespace App\\Symfony\\EventListener;

use Symfony\\Component\\HttpKernel\\Event\\FilterResponseEvent;

class NoCacheListener
{
    /\*\*
     \* @param FilterResponseEvent $event
     \*/
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $route = $event->getRequest()->attributes->get('\_route');

        if (!in\_array($route, \['app\_front\_cart\_show', 'app\_front\_orders\_flow\_display'\])) {
            return;
        }

        $response = $event->getResponse();
        $response->setMaxAge(0);
        $response->headers->addCacheControlDirective('must-revalidate');
        $response->headers->addCacheControlDirective('no-store');
        $response->headers->addCacheControlDirective('no-cache');
    }
}

Source: Matt Brictson's article

Written by

Yann Rabiller
Yann Rabiller

Comments