Search code examples
laravelcsrf-protectionpage-caching

Laravel - How to make CSRF token work with HTML Cache?


As far as i know HTML cache will generate a static html file but CSRF needs to be refreshed on each time load page so is there a way to make CSRF token work with HTML Cache?


Solution

  • Since CSRF tokens are normally included in the form input, page caching would void the ability to randomize that input per user.

    You can use ajax to load data into the cached page.

    One solution would be to load the entire HTML of the form through ajax into the cached page. Another solution would be to load just the token through an ajax request into the form. This may be something you can program into your site, to retrieve a token and insert into all of your forms on page load or add it to the form submission process. This article discusses implications of getting a CSRF token through an ajax request.