atfinho
4 months ago
146
2
Laravel

Subscribe to private channels pusher

Posted 4 months ago by atfinho

Hey guys I'm trying to subscribe to private channels in pusher and I'm using react js & Laravel after reading some of their documentation it was mentioned that private channels need authentication and I should pass 'X-CSRF-Token' when I listen to this kind of channels + adding a prefix before the name of channel " private " ..

Anyway in my front side this is my code to listen for private channels


 componentDidMount() {
 
    const pusher = new Pusher('23525de46fdea6e17af3', {
   
      auth: {
        headers: {
          auth: { 
            headers: { 
              'X-CSRF-Token': localStorage.userToken 
            }
           }
        }
      },
      cluster: 'eu',
      encrypted: true
    });
    const channel = pusher.subscribe('private-channel');
    channel.bind('App\Events\NewPost', data => {

alert();
   
   }

 localStorage.userToken 

the code above gives me access to user token that I get from passport when I authorize any user to my app..

this throws an error of : POST http://localhost:3000/pusher/auth 404 (Not Found)

I tried also to pass csrf_token from controller doing something like this

 $token=csrf_token()
// pass it to response

$token returns always null

this is my event code

<?php

namespace App\Events;

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 NewPost implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

   public $text;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($text)
    {
        $this->text=$text;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel');
    }
}


I don't know how to fix this ..

I hope someone can help me to get through it thank you in advance

Please sign in or create an account to participate in this conversation.