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

geerizzle's avatar

Inertia JS post is invalid - if a few seconds after page load?

I have an issue when a page has first loaded, and a button is clicked, then it fails due to an invalid Inertia response

 function addToCart(id) {
    form.post('/add-to-cart', {preserveScroll: true, preserveState:true,  onSuccess:(success) => {state.showModal = true});
  }

onError() doesn't capture this issue, but the following does and retries the function:

  Inertia.on('invalid', (event) => {
    event.preventDefault();  
    if(event.detail.response.config.url.includes('remove-from-cart')) {
       removeFromCart(form.id)
    }
    if(event.detail.response.config.url.includes('add-to-cart')) {
      addToCart(form.id) 
    }
  })

This works, but why should I need to do this? Why is Inertia.post returning invalid initially? If I wait 3-5 seconds after the page has visibly laded it works fine.

I assume something has not mounted or it can't find the CSRF token? This is in the meta tag like usual.

Any ideas on what I need to wait for before submitting a function or how to ensure the csrf is being used etc?

0 likes
1 reply
geerizzle's avatar

So the docs say: "Once the Inertia app has been booted, all subsequent requests to the site are made via XHR with a X-Inertia header set to true. This header indicates that the request is being made by Inertia and isn't a standard full-page visit."

Checking the response I think this is the issue. How do I make sure this subsequent request is treated as such?

Please or to participate in this conversation.