Laravel Livewire: how to disable CSRF token to embed a component on iframe

If you try to directly embed a Livewire component on another application using an iframe, you may receive a message like that when the component is rendered:

An embedded page at WEBSITE says: This page has expired due to inactivity. Would you like to refresh this page?

It happens because, by default, Laravel routes with the POST method require a CSRF token to protect them from malicious cross-site requests, and Livewire makes POST requests to update the component state:

As you can see, the Livewire routes that updates the component state follow this pattern:

POST /livewire/message/{component-name-separated-with-dashes}

So, to avoid this behavior on a specific component, you just need to add your component route to the $except property on the VerifyCsrfToken middleware.

class VerifyCsrfToken extends Middleware { 
    
    protected $except = [ 
        'stripe/*', 
        'voting/*/embed', 
        'livewire/message/embed-voting', 
    ];

}

I would not recommend disabling CSRF for all Livewire routes adding livewire/* to the VerifyCsrfToken middleware, as it may expose all your components to potential malicious cross-site requests.

It is better to explicitly disable it only for components that will be publicly available for iframe embedding.

That is it. I hope this small tutorial is helpful for you.

Cheers.


Tiago Rodrigues

by Tiago Rodrigues

Software Developer. Creator of Vemto. Find me on Twitter.

Vemto

A Desktop Laravel code generator that will power the way you start new Laravel Projects.
More Details

Contacts

contact@vemto.app
Ara├žatuba, Brazil