Skyline

13 Best Practices for Livewire Security

· 7 min read · Boring Observability

Verified against Livewire 4.4.9 · Laravel 13

A Livewire component reads like server code, but its public properties and public methods are an API. The browser can set any public property with $wire.set() and call any public method with whatever arguments it likes, and on the next request Livewire hydrates the values and binds the models it was sent. Nothing throws when a component trusts one of those values, so the mistake ships, and it stays until somebody opens the devtools.

The practices below apply to Livewire 3 and 4, with a note where an attribute only exists in 4. Most of them come down to one habit: treat public state and action arguments as input from the user, because that is what they are.

1. Lock every property the server sets#

This component authorizes the booking in mount() and keeps its id for later:

class ShowBooking extends Component
{
    public int $bookingId;

    public function mount(Booking $booking): void
    {
        $this->authorize('view', $booking);

        $this->bookingId = $booking->id;
    }

    public function cancel(): void
    {
        Booking::findOrFail($this->bookingId)->cancel();
    }
}

A visitor allowed to see booking 41 runs $wire.set('bookingId', 42) in the console and clicks Cancel. The check ran for 41, and the cancel runs on 42. Mark the property #[Locked], and the same call throws CannotUpdateLockedPropertyException instead:

use Livewire\Attributes\Locked;

#[Locked]
public int $bookingId;

Lock anything only the server decides: ids, a tenant, a role, a price. Leave unlocked what wire:model binds, because locking an input throws the same exception on the first keystroke. Those properties are input, and rule 8 covers them.

2. Keep the model in the property, not its id#

Livewire sends a model property to the browser as its class and key only, inside the snapshot its checksum protects, and refuses writes into it:

public Booking $booking;

public function mount(Booking $booking): void
{
    $this->authorize('view', $booking);

    $this->booking = $booking;
}

// $wire.set('booking.id', 42) throws "Can't set model properties directly"

Replacing the whole property doesn't work either. After $wire.set('booking', 42), Livewire rebuilds the property from the key in the snapshot and ignores the value the browser sent, so it still holds booking 41. Livewire's documentation recommends this over a locked id for most cases, since the record's identity is protected without an attribute to forget. The model's attributes stay on the server too, because only the key travels.

The protection only applies while the property holds a model, so type it. A typed ?Booking that is still null rejects a value from the browser, but an untyped public $booking that is still null takes whatever the browser sends.

3. Lock server-owned fields inside Form objects#

A Livewire\Form is a set of public properties like any other, one level down, and $wire.set('form.postId', 2) works. Locking the form itself doesn't help: every wire:model="form.title" then throws CannotUpdateLockedPropertyException. Lock the field, in the Form class:

class PostForm extends Form
{
    #[Locked]
    public int $postId;

    #[Validate('required|max:120')]
    public string $title = '';
}

4. Authorize every action that receives a model or an id#

Any public method a component defines, apart from render(), can be called from the browser with any arguments. When a parameter is typed as a model, Livewire binds it from whatever id arrives:

public function delete(Post $post): void
{
    $post->delete();   // $wire.delete(123) deletes post 123, whoever owns it
}

Check the record before you touch it:

public function delete(Post $post): void
{
    $this->authorize('delete', $post);

    $post->delete();
}

An untyped id needs the same check after the lookup: delete(int $id) followed by Post::findOrFail($id) is the same hole without the binding. Route middleware such as can:update,post checks the record in the page's URL, not one an action receives as an argument. And a public helper you only meant to call from PHP is an action too, so make helpers protected or private.

5. Check #[On] handlers the same way#

The browser can dispatch any event a component listens for. Running Livewire.dispatch('archive-post', { post: 7 }) in the console calls this handler with post 7 bound, exactly as if another component had sent it:

#[On('archive-post')]
public function archive(Post $post): void
{
    $this->authorize('update', $post);

    $post->archive();
}

Treat every listener as an action: authorize the record, and validate any plain values in the payload.

6. Put component-wide checks in booted(), not mount()#

mount() runs once, when the component first renders. The requests after that, for every click and every wire:model update, rebuild the component from its snapshot and skip mount(). A check there protects the first page load and nothing else.

For a check that should cover every request, use booted():

public Team $team;

public function mount(Team $team): void
{
    $this->team = $team;
}

public function booted(): void
{
    $this->authorize('view', $this->team);
}

booted() runs after mount() on the first request and after the properties are restored on every later one. boot() also runs on every request, but on the first one it runs before mount(), when $this->team isn't set yet.

7. Give #[Authorize] a target that resolves#

Livewire 4.3 added #[Authorize], which runs a gate check before the action. Livewire looks the target up at runtime as a class name, then a parameter of the method, then a property of the component, and a name that matches none of them doesn't raise an error:

#[Authorize('update', 'psot')]       // no such class, parameter or property: the gate gets null
public function save() {}

#[Authorize('delete', 'comment')]    // untyped: the gate gets the raw id the browser sent
public function remove($comment) {}

#[Authorize('delete', 'comment')]    // the bound Comment
public function destroy(Comment $comment) {}

Given null or a bare id, Laravel's gate finds no policy, so PostPolicy::update() never runs. Usually that is a 403 for everyone, which a test catches. With a Gate::before() hook, such as one that lets admins through, or a Gate::define() under the same ability name, the gate decides without the record. Type the parameter, and spell the target as it appears in the signature.

8. Call validate() before an action writes#

#[Validate] on a property validates it when the browser updates it. A failure records the error in the error bag and stops there. The action in the same request still runs, with the invalid value:

#[Validate('required|max:120')]
public string $title = '';

public function save(): void
{
    $this->validate();   // without this, an empty or 5,000-character title is saved

    Post::create(['title' => $this->title]);
}

The same goes for a rules() method, which does nothing until validate() or validateOnly() reads it. Start every action that writes with $this->validate().

9. Keep $rules, $listeners and the other settings protected#

Livewire has no exclusion list for its own configuration properties. A public one is client state like any other:

public array $rules = ['title' => 'required|max:120'];
// $wire.set('rules', { title: 'nullable' }) and validate() now accepts anything

protected array $rules = ['title' => 'required|max:120'];

The same applies to $messages, $validationAttributes, $validationCustomValues, $listeners, $queryString and $paginationTheme. Declare them protected, or move the rules into a protected function rules(), as Livewire's documentation does.

10. Don't cache per-user data in a shared computed property#

#[Computed(cache: true)] stores the result under the component's name and the method's name, so every visitor shares one entry, for an hour by default:

#[Computed(cache: true)]
public function myOrders()
{
    return Order::whereBelongsTo(auth()->user())->get();   // everyone sees the first caller's orders
}

persist: true keys the entry on the component instance instead, which is the one to use for anything that depends on the user. A key: argument is used as a literal string, so key: 'orders-{userId}' is still one entry for everybody. And a persisted value that reads a property the browser can change goes stale when the property does, so clear it in the property's update hook:

public function updatedSearch(): void
{
    unset($this->results);
}

11. Don't put #[Url] on a property you lock#

#[Locked] blocks updates sent by the browser. #[Url] reads the query string while the component mounts, which isn't an update, so the lock never sees it:

#[Locked]
#[Url]
public int $tenantId = 0;   // ?tenantId=99 sets it to 99

A value in the URL is chosen by the visitor. If the server owns it, drop #[Url]; if the visitor may choose it, drop #[Locked] and check it like any other input.

12. Turn getFooProperty() accessors into #[Computed] methods#

The old getTotalProperty() accessor still works as $this->total, but it is a public method, so the browser can call it and read the result: await $wire.getTotalProperty(). A #[Computed] method is read the same way in PHP and Blade, and Livewire refuses to call it from the client:

#[Computed]
public function total(): Money
{
    return $this->order->total;
}

Making the accessor protected isn't a fix, because Livewire only recognises public ones and $this->total stops working.

13. Check every component in CI#

Each of these is one missing line in a component that otherwise works, which is the kind of thing code review misses and static analysis doesn't. wirestan is our free PHPStan extension for Livewire, and it checks rules 1 and 4 to 12 on every run. It doesn't look inside Form classes, so rule 3 is still yours to review, and it checks rule 4 only where the parameter is typed as a model.

On an existing app, generate a baseline with --generate-baseline so the build fails only on new findings, then work through the old ones. The locking rule reads each component's Blade views, so it doesn't ask you to lock a property that wire:model binds. It also catches six Livewire mistakes that aren't security holes but throw once the code runs, such as writing to a #[Reactive] property.

Frequently asked questions

Can users change Livewire public properties from the browser?

Yes. Any public property declared on a component can be set from the browser console with $wire.set('name', value), and Livewire applies it on the next request. Mark properties that only the server should set with #[Locked], which makes such an update throw CannotUpdateLockedPropertyException, or store the model itself in the property, whose identity Livewire protects.

Should I store a model or its id in a Livewire property?

The model, in most cases. Livewire sends a model property to the browser as its class and key only, inside the checksummed snapshot, and refuses writes into it: $wire.set('post.id', 2) throws. A plain integer id is an ordinary public property the browser can change unless it is marked #[Locked].

Do I need to authorize Livewire actions if the page route is already protected?

Yes. Any public method on a component can be called from the browser with any arguments, and a parameter typed as a model is bound from whatever id the browser sends. Route middleware checks the record in the page's URL, not the one an action receives. Call $this->authorize() in the action, or use #[Authorize] on Livewire 4.3 and later.

Does #[Validate] stop a Livewire action from running?

No. #[Validate] validates a property when the browser updates it, and a failure only records the error. An action called in the same request still runs with the invalid value. Call $this->validate() at the start of every action that writes.

Is #[Computed(cache: true)] shared between users?

Yes. With cache: true Livewire stores the result under the component's name and the method's name, so every visitor reads the same entry, for 3600 seconds by default. A key: argument is used as a literal string. Use persist: true, which keys the entry on the component instance, for anything that depends on the current user.

Is authorization in mount() enough in Livewire?

No. mount() runs only when the component first renders; every later request for a click or a wire:model update rebuilds the component from its snapshot without calling mount(). Put a check that should cover every request in booted(), which runs after mount() on the first request and after the properties are restored on later ones.