Steps to use Livewire with Acorn 4.0

Hej,

since roots/acorn:4.0 we have official support forlivewire/livewire (Enhanced Router Compatibility (Including Livewire Support) And Filters For Early Service Container Overrides by broskees · Pull Request #291 · roots/acorn · GitHub).

I tried to follow the mentioned steps in the related PR and found some needed changes (for me). But unfortunately, although it first seems to work, I ran into an issue related to the session / nonce / CSRF.

Currently the @livewireScripts or the ESM version @livewireScriptConfig won’t set a CSRF token, which will break on events like wire:click or wire:submit.

Has anyone a hint, why the csrf_token() will return null? Am I missing something?

Best,
Daniel

… I tried to debug this and am quite not sure if I miss something fundamental.
It seems that the session will not be persistent between different requests. Secondly, at every point in code, the function csrf_token() will return null.

However, at the moment, I’m applying the following workaround to ensure that the Livewire components function properly:

In the layout file, I add:

<meta name="csrf-token" content="{{ Str::random(40) }}">

This will provide the Livewire JS code the required token.

1 Like

I’ve encountered same issue in the past where the CSRF token wasn’t generated on pages managed by WordPress itself.

I guess it’s due to WordPress pages aren’t managed by the Laravel router, so doesn’t trigger a middleware that initiates the session which generates the token.

This is my current workaround:

/**
 * Start Laravel Session after WordPress loaded.
 */
add_action('wp_loaded', fn () => app('session')->isStarted() || app('session')->start());