Ad

Pusher With Vue And Laravel API Not Working

- 1 answer

I am using Vue SPA and Laravel. I have google it for hours and tried many things but I can't find a way to make it work.

In index.html I have

<meta name="csrf-token" content="{{ csrf_token() }}"> 

This is my subscribe method:

subscribe() {
  let pusher = new Pusher('key', {
    cluster: 'ap1',
    encrypted: true,
    authEndpoint: 'https://api_url/broadcasting/auth',
    auth: {
      headers: {
        'X-CSRF-Token': document.head.querySelector(
          'meta[name="csrf-token"]'
        )
      }
    }
  })
  let channel = pusher.subscribe(
    'private-user.login.' + this.user.company_id
  )
  channel.bind('UserLogin', data => {
    console.log(data)
  })
}

I am getting a 419 error saying: "expired due to inactivity. Please refresh and try again."

If you didn't noticed there I am trying to listen to a private channel.

Ad

Answer

I found the solution I hope it can help others:

In front end:

  let pusher = new Pusher('app_key', {
    cluster: 'ap1',
    encrypted: true,
    authEndpoint: 'https://api_url/broadcasting/auth',
    auth: {
      headers: {
        Authorization: 'Bearer ' + token_here
      }
    }
  })
  let channel = pusher.subscribe(
    'private-channel.' + this.user.id
  )
  channel.bind('event-name', data => {
    console.log(data)
  })

As you can see above no need to use csrf token, instead use the jwt token.

In the backend, go to BroadcastServiceProvider and change this:

Broadcast::routes(); to Broadcast::routes(['middleware' => ['auth:api']]);

Ad
source: stackoverflow.com
Ad