Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

salahaldain-abduljalil's avatar

prevent Back History matter.

welcome guys I have small problem I am using this middleware to let users can't navigate the browser back in some cases but it does not why please help me

public function handle(Request $request, Closure $next) { $response = $next($request);

if (session()->has('notify')) {
    $response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
    $response->headers->set('Pragma', 'no-cache');
    $response->headers->set('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT');
}

if (session()->has('disable_back_button')) {
    $response->setContent($response->getContent() . '
    <script>
        history.pushState(null, null, location.href);
        window.onpopstate = function () { 
            history.go(1); 
            history.pushState(null, null, location.href);
        };
        window.addEventListener("popstate", function(event) {
            history.go(1);
            history.pushState(null, null, location.href);
        });
    </script>');
}

return $response;

}

Best Regards....

0 likes
2 replies
jlrdw's avatar

Did you add tour prevent-back-button to your middleware?

Please or to participate in this conversation.