calin.ionut
3 months ago

CSRF token mismatch (the server responded with a status of 419)

Posted 3 months ago by calin.ionut

On my product page I am using ajax to add to cart a product which is working ok.

The problem is .... after a while...if the page has not been refreshed, the server change the csrf token.

So without refresh the page after a while.... I cannot make the post request because

 Failed to load resource: the server responded with a status of 419 (unknown status)

and on the server

{message: "CSRF token mismatch.", exception: "Symfony\Component\HttpKernel\Exception\HttpException",…}
exception: "Symfony\Component\HttpKernel\Exception\HttpException"
file: "/var/www/test/vendor/laravel/framework/src/Illuminate/Foundation/Exceptions/Handler.php"
line: 208
message: "CSRF token mismatch."
trace: [{,…}, {file: "/var/www/test/app/Exceptions/Handler.php", line: 51, function: "render",…},…]

How do you guys handle this problem?

I am thinking like this .... but I am not sure how to do it:

  1. handle this exception on the server and return the new csrf token
  2. catch in the ajax call (for this status code) the new token and try to make the post again (without refresh the page)

What do you think?

Please sign in or create an account to participate in this conversation.