A user spends ten minutes on a long form, their Wi-Fi blinks, they hit Save, and the work is gone. The usual explanation is "Livewire lost the state", and the usual fix is a pile of JavaScript that scrapes the form into localStorage on every keystroke. Before writing any of that, it's worth knowing what Livewire actually does when a request fails, because it isn't what most people assume.
Everything below was checked against Livewire 4's client source and run in headless Chrome with the network switched off mid-form, against a fresh Laravel app on the current release.
What Livewire does when the network drops
Livewire keeps two copies of each component's data in the browser: the last state the server confirmed, and the current state with the user's edits. When it sends a request, it computes the difference between the two and posts just those updates. Only a successful response replaces the confirmed state.
So when fetch fails because the device is offline, nothing is rolled back. The inputs keep their values, the component's properties keep the edits, and the next request that goes out carries the same updates again. Livewire fires its onFailure interceptors, rejects the promise returned by the action, and shows no error modal. In my test, after a failed Save with the network off, $wire.title and the input both still held what I'd typed.
A few other things happen automatically. wire:poll pauses while the browser reports it's offline, and the wire:offline directive toggles elements when the browser's online and offline events fire. That's all the built-in offline support there is. Livewire doesn't queue the failed action and replay it later.
Where the data actually goes missing
If failed requests don't lose state, what does? In practice, three things.
The page goes away. The user's edits live only in that tab's memory. A reload, a closed tab, a phone that discards a background tab, or wire:navigate to another page throws them away. A user who sees nothing happen when they click Save often reloads, which is the worst thing they can do.
The session expired during the outage. This one surprised me. When I deleted the session while the form was open and then saved, the request hit the auth middleware, got redirected to the login route, and Livewire followed that redirect with the whole page. Everything typed into the form was gone. You might expect a 419 here instead. Laravel's PreventRequestForgery middleware accepts same-origin requests based on the browser's Sec-Fetch-Site header before it ever looks at the token, as the origin verification docs explain. Browsers only send that header over HTTPS (localhost counts), and older browsers or plain HTTP fall back to token checks, where an expired session does produce a 419. Livewire answers a 419 with a "This page has expired" confirm that reloads the page. Either way, the form is gone.
The save went through but the response didn't. The connection drops after the server committed the insert but before the browser got the reply. The client sees a failure, the user or your retry logic sends it again, and now there are two records.
The fix has to cover all three: keep a copy of the input that survives the page, retry once the connection is back, and make the save safe to repeat.
Make the save idempotent first
Start on the server, because a retry without idempotency turns a lost response into a duplicate. Give each form instance a submission ID when it mounts, and save with updateOrCreate keyed on that ID and the user:
<?php
namespace App\Livewire;
use App\Models\Article;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Component;
class CreateArticle extends Component
{
public string $submissionId = '';
public string $title = '';
public string $body = '';
public function mount(): void
{
$this->submissionId = (string) Str::uuid();
}
public function save(): bool
{
$validated = $this->validate([
'submissionId' => ['required', 'uuid'],
'title' => ['required', 'string', 'max:200'],
'body' => ['required', 'string'],
]);
$article = Article::updateOrCreate(
['user_id' => Auth::id(), 'submission_id' => $validated['submissionId']],
['title' => $validated['title'], 'body' => $validated['body']],
);
$this->redirect(route('articles.show', $article), navigate: true);
return true;
}
public function render()
{
return view('livewire.create-article');
}
} Back it with a unique index so a race between two retries can't slip past the updateOrCreate lookup:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->uuid('submission_id');
$table->string('title');
$table->text('body');
$table->timestamps();
$table->unique(['user_id', 'submission_id']);
});
}
}; Two details matter here. $submissionId is a public property, so the client can change it. That's deliberate, because the draft we restore after a reload needs to bring the original ID back with it. It's also why the lookup includes user_id: a user who tampers with the ID can only ever collide with their own submissions. And save() returns true only after the write, which gives the JavaScript a clean signal to tell success from a validation failure.
Show the user what's happening
The cheapest improvement is telling people they're offline before they click anything. wire:offline shows an element while the browser is offline, and .attr adds an attribute for that period:
<form wire:submit="save">
<p wire:offline>
You're offline. Your changes are kept in this browser and will be sent when you reconnect.
</p>
<input type="text" wire:model="title">
@error('title') <span>{{ $message }}</span> @enderror
<textarea wire:model="body"></textarea>
@error('body') <span>{{ $message }}</span> @enderror
<button type="submit" wire:offline.attr="disabled">Save</button>
<p id="save-status" hidden></p>
</form> Don't lean on the banner too hard. The browser's notion of "offline" only covers a missing network interface. A captive portal, a dead upstream router or a server that's down all report as online, and requests still fail. That's why the failure handler below matters more than the banner.
Keep a draft that survives the page
This script goes in the same Blade view, under the form. Class-based components wrap it in @script; single-file components can use a bare <script> tag. It writes the draft to localStorage whenever a bound property changes, restores it when the component loads, retries a failed save when the browser comes back online, and clears the draft only after a real success:
@script
<script>
const storageKey = 'draft:create-article'
const status = $wire.$el.querySelector('#save-status')
let retryWhenOnline = false
const saved = localStorage.getItem(storageKey)
if (saved) {
const draft = JSON.parse(saved)
$wire.title = draft.title ?? ''
$wire.body = draft.body ?? ''
if (draft.submissionId) {
$wire.submissionId = draft.submissionId
}
}
const persist = () => {
localStorage.setItem(storageKey, JSON.stringify({
title: $wire.title,
body: $wire.body,
submissionId: $wire.submissionId,
}))
}
$wire.$watch('title', persist)
$wire.$watch('body', persist)
$wire.intercept('save', ({ onSend, onSuccess, onFailure }) => {
onSend(() => persist())
onSuccess((saved) => {
if (saved === true) {
localStorage.removeItem(storageKey)
}
})
onFailure(() => {
retryWhenOnline = true
status.textContent = 'Not saved yet. We will retry when your connection is back.'
status.hidden = false
})
})
window.addEventListener('online', () => {
if (! retryWhenOnline || ! $wire.$el.isConnected) {
return
}
retryWhenOnline = false
status.hidden = true
$wire.save()
})
</script>
@endscript A few choices in there are deliberate.
$wire.$watch fires on changes to the component's client-side state, so it works with plain deferred wire:model. You don't need wire:model.live, and you don't send a request per keystroke just to keep a backup. The guide to wire:model.live covers when live binding is worth the traffic; draft safety isn't one of those cases.
The action interceptor is scoped to save with $wire.intercept('save', ...), so it doesn't fire for unrelated calls, and Livewire removes component-level interceptors when the component is removed. The window listener isn't cleaned up automatically, which is why it checks $wire.$el.isConnected before doing anything. Both interceptor levels and their callbacks are listed in the JavaScript interceptors reference.
The draft is cleared in onSuccess only when the action returned true. A validation error isn't a successful save, and clearing the draft there would throw away exactly the input the user needs to fix.
In headless Chrome I typed into the form, cut the network, and submitted. The status message appeared, the draft sat in localStorage with its submission ID, and the inputs kept their values. When I restored the network, the online event fired, the retry saved the article, the draft was cleared, and the page moved on to the new article. Reloading a half-filled form brought back the text and the same submission ID.
Handle an expired session on purpose
The draft is what saves you from the session-expiry redirect: the user logs in again, comes back to the form, and the script restores their text. If your app does see 419s, from plain-HTTP environments or older browsers, you can replace Livewire's confirm dialog with something calmer. Register it once, globally, after Livewire boots:
document.addEventListener('livewire:init', () => {
Livewire.interceptRequest(({ onError }) => {
onError(({ response, preventDefault }) => {
if (response.status === 419) {
preventDefault()
window.location.reload()
}
})
})
}) Reloading is the honest fix. A stale page can't recover a session from JavaScript, and refreshing the CSRF token doesn't help a user whose login has expired. With the draft in localStorage, the reload costs them nothing.
What not to store in the browser
localStorage is plain text, readable by any script on your origin and left on shared machines after logout. Keep it to content the user typed and would expect to find again. Don't put payment details, passwords or anything sensitive in a draft. On a shared-device app, clear drafts on logout.
It's also per browser. A user who switches from laptop to phone won't see the draft. If that matters, save server-side drafts on a timer with wire:poll or a debounced wire:model.live, and keep the local copy for the moments when the network isn't there. Livewire's #[Session] attribute persists a property across reloads too, but it needs a successful request to store anything, so it doesn't help with edits made while offline.
Finally, keep the key specific. One key per form type is fine for a "new article" screen. For editing existing records, include the record ID in the key, or two tabs editing different articles will overwrite each other's drafts.
Testing the server side
The browser parts need a real browser, and Chrome DevTools' network throttling set to Offline is the quickest manual check. The idempotency guarantee can be covered in an ordinary feature test, which is where regressions tend to sneak in:
<?php
namespace Tests\Feature;
use App\Livewire\CreateArticle;
use App\Models\Article;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;
class CreateArticleTest extends TestCase
{
use RefreshDatabase;
public function test_retrying_a_save_does_not_duplicate_the_article(): void
{
$user = User::factory()->create();
$component = Livewire::actingAs($user)
->test(CreateArticle::class)
->set('title', 'Offline drafts')
->set('body', 'First attempt');
$component->call('save')->assertRedirect();
$component->set('body', 'Second attempt')->call('save');
$this->assertSame(1, Article::count());
$this->assertSame('Second attempt', Article::first()->body);
}
public function test_a_restored_draft_reuses_its_submission_id(): void
{
$user = User::factory()->create();
$first = Livewire::actingAs($user)->test(CreateArticle::class);
$submissionId = $first->get('submissionId');
$first->set('title', 'A')->set('body', 'B')->call('save');
Livewire::actingAs($user)
->test(CreateArticle::class)
->set('submissionId', $submissionId)
->set('title', 'A')
->set('body', 'B again')
->call('save');
$this->assertSame(1, Article::count());
}
} The second test is the one that matters for flaky connections. It simulates the case where the first save committed, the browser never heard back, the user reloaded, and the restored draft submitted again from a brand-new component instance. One row, not two.
If the same form also needs a confirmation step before destructive actions, wire:confirm composes fine with all of this, since a cancelled confirm never sends a request.











![Form Validation with Livewire's #[Validate] Attribute](/_next/image?url=https%3A%2F%2Ftechversedaily.com%2Fstorage%2Fposts%2FB7cgZr17OdhYHzi44oSxaAyFXr4fdlkjAiguc8i4.png&w=3840&q=75)

