Skip to content

Instantly share code, notes, and snippets.

@aerni
Last active September 4, 2024 18:11
Show Gist options
  • Save aerni/150450376f088cf8d904e6bce9289888 to your computer and use it in GitHub Desktop.
Save aerni/150450376f088cf8d904e6bce9289888 to your computer and use it in GitHub Desktop.
Learn how to use Livewire together with Statamic's static caching

How to use Livewire with Statamic static caching

Since Statamic 3.4.8

As of Statamic 3.4.8, Livewire works with Statamic's Half and Full Measure static caching without any additional configuration. This is due to the concept of replacers, which takes care of replacing Livewire's CSRF token.

Caveats

There is a catch, though. On the first page load, Statamic will cache the first render of the Livewire component. This can be an issue with components that display dynamic content like entries in random order. In this example, the order won't be random on subsequent page loads, but will always show in the order that it was first cached in.

If your component simply shows the latest articles in descending order, and you clear the cache whenever an entry is saved, you don't have to worry about this, though.

Solutions

Cache Tag

To get around this issue, you can use the {{ nocache }} tag around the Livewire component. This works for both Half Measure and Full Measure static caching. Just keep in mind, that you don't have much control over the loading state when using Full Measure. Learn more about this here.

Defer Loading

If you want to use Full Measure static caching, it might be a good idea to use Livewire's Defer Loading feature instead of using the {{ nocache }} tag. This feature allows you to have more control over the loading state of the component. You could even add a loading skeleton if you wanted to.

Before Statamic 3.3.20

Follow this guide to make Laravel Livewire work with Statamic's static caching. Note that this only works with Half Measure static caching. Livewire won't work with Full Measure static caching.

Exclude the Livewire endpoint from the static cache in config/statamic/static_caching.php.

'exclude' => [
    '/livewire*',
],

Exclude the Livewire endpoint in the VerifyCsrfToken middleware in app/Http/Middleware/VerifyCsrfToken.php.

protected $except = [
    '/livewire*',
];

That's it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment