question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

CSRF token mismatch.

See original GitHub issue

I get the above error when I run laravel-echo-server start. None of the issues I’ve searched in the issue tracker have helped so far. The event is also not being broadcasted. Queue and Broadcast drivers have been set to Redis. Broadcast service provider was correctly registered in app.php.

I’m just using a default laravel app installation btw.

Full log: https://paste.laravel.io/bdcbf334-b7ce-46d5-b0a8-0b49703cc546#1,21

JS code:

import Echo from 'laravel-echo';

window.io = require('socket.io-client');

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001',
    authEndpoint: "/broadcasting/auth",
});

window.Echo.private(`test`)
    .listen('.user.registered', function (e) {
        console.log(e);
    });

Channels:

Broadcast::channel('App.User.{id}', function ($user, $id) {
    return (int) $user->id === (int) $id;
});

Broadcast::channel('test', function ($user) {
    return true;
});

Event:

<?php

namespace App\Events;

use App\User;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class UserRegistered implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $user;

    public function __construct(User $user)
    {
        $this->user = $user;
    }

    public function broadcastOn()
    {
        return new PrivateChannel('test');
    }

    public function broadcastAs()
    {logger('broadcast as');
        return 'user.registered';
    }

    public function broadcastWith()
    {
        return ['id' => $this->user->id];
    }
}

I call the event with:

event(new \App\Events\UserRegistered(Auth::user()));

Really at a loss here. No idea why I get the error after starting the web server or why I can’t broadcast events.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:18 (1 by maintainers)

github_iconTop GitHub Comments

2reactions
tlaverdurecommented, Aug 6, 2019

Hey there!

If a meta tag with the csrf-token as the value is found, it will be automatically passed by echo as the header: X-CSRF-TOKEN.

    protected setOptions(options: any): any {
        this.options = Object.assign(this._defaultOptions, options);


        if (this.csrfToken()) {
            this.options.auth.headers['X-CSRF-TOKEN'] = this.csrfToken();
        }


        return options;
    }

Inspired by: https://laravel.com/docs/5.8/csrf#csrf-x-csrf

You could do it manually too:

window.Echo = new Echo({
    broadcaster: 'socket.io',
    host: window.location.hostname + ':6001',
    authEndpoint: "/broadcasting/auth",
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
1reaction
marcnewtoncommented, Mar 9, 2020

I finally got pragmatic headers to work, Since I built a full Same Domain SPA the CSRF token is pragmatically stored in a state that is set via an axios interceptor looking for a token change so I get the token a bit later and it will update when the user session state changes or the token is invalidated and renewed.

None of the solutions above worked for setting the token AFTER the instance is crated, here is a solution that does:

import io from 'socket.io-client'

window.Echo = new LaravelEcho({
  broadcaster: 'socket.io',
  host: { path: '/socket.io' },
  client: io
})

// A FEW MOMENTS LATER...
// axios call to login a user, a new token is created and needs to be set.
window.Echo.connector.options.auth.headers['X-CSRF-TOKEN'] = token

The problem is if you login a user via ajax and do not reload the page then the token from the meta tag is not going to match anymore since Laravel changes the token value when the user session state changes. An example of session state change is when a Guest Session becomes a User session (Login) or User Session becomes Guest session (Logout).

My use case looks like this:

vm.$on('user:authenticated', authenticated => {
  if (authenticated && vm.user.id != null) {
    vm.$Echo.connector.options.auth.headers = vm.$http.defaults.headers.common

    vm.$Echo.private(`App.User.${vm.user.id}`).notification(response => {
      console.info('Private Notification', response)
    })
  }
})
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to fix the “CSRF token mismatch error” message
The “Invalid or missing CSRF token” message means that your browser couldn't create a secure cookie or couldn't access that cookie to authorize...
Read more >
Laravel csrf token mismatch for ajax POST Request
The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax...
Read more >
What should I do if a "CSRF token mismatch" message ...
A "CSRF token mismatch" message will display on the Buy page if it has been idle for more than 15 minutes, indicating that...
Read more >
CSRF token error messages - Todoist
CSRF tokens mismatch ... This error message is caused by privacy extensions. If you are running any privacy extensions such as Ghostery or...
Read more >
Laravel 8.x 419 "CSRF token mismatch" - Laracasts
I am using Laravel only as api and php file, jquery as frontend. I am using jquery ajax. I know that I should...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found