DEV Community

loading...

Using laravel-echo with Nuxt.js

eichgi profile image Hiram ・3 min read

Hi devs, last day I was trying to configure my Nuxt.js client so it can consume public and private channels from my backend which is built with Laravel along the Laravel Websockets package.

So this post is basically like a guide for me and everyone else in the same situation, my current stack is as follows:


The following is the Vue plugin I created with the basic configuration you have to define in order to access and authenticate private channels:

import Vue from 'vue';
import Echo from 'laravel-echo';

const echo = {};

echo.install = function (Vue) {
  Vue.prototype.$pusher = require('pusher-js');
  Vue.prototype.$echo = new Echo({
    authEndpoint: 'http://your-domain.test/api/broadcasting/auth',
    auth: {
      headers: {
        Authorization: 'Bearer XXXXXXXXXXXX',
      }
    },
    broadcaster: 'pusher',
    key: 'your-key',
    wsHost: 'your.websocket.host',
    wsPort: 443,
    encrypted: true,
    disableStats: false,
  });
};

Vue.use(echo);

This is the description for the parameters we are going to use and what they are for:

auth_endpoint: Since you are using Nuxt or Vue it means you are generating a client that might be hosted or located in a different place than your backend, so you have to specify how to reach the backend.

auth: For this scenario I am using Laravel Sanctum authentication package, this is the reason I have to specify the Bearer token I am using.

broadcaster: I am using pusher-js which is the package required for Laravel-websockets.

The 3 parameters above are the most important since they are not often showed as examples and are the keys so we can connect to our decoupled backend. The rest of them are necessary on any configuration.


Once you defined the Echo instance, you can define your channels on any component:

this.$echo.private('App.User.' + this.$auth.user.id)
        .listen('GeneralEvent', e => {
          console.log("GENERAL EVENT: ", e);
        })
        .notification(notification => {
          console.log("NOTIFICATION: ", notification);
        });

It is also important to add the following routes on your api.php routes file given you are using api authentication. As you can see we are specifying the sanctum middleware. Unlike web routes the session authentication is already applied when you enable the BroadcastServiceProvider.php file.

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

At this point you should be able to authenticate your private channels. But another important thing with this configuration is the way we are going to set our authentication token into our plugin. Luckily for us there is a package created by the Nuxt community:

I decided to go with this package instead my own plugin because I wasn't sure how to handle the auth mechanism, and also because I am using the nuxt-auth package which you can pair with laravel-echo package easily.

So I ended up with the following configuration in nuxt.config.js

buildModules: [
    ['@nuxtjs/laravel-echo', {
      broadcaster: 'pusher',
      authModule: true,
      connectOnLogin: true,
      authEndpoint: process.env.API_URL + '/broadcasting/auth',
      key: process.env.WEBSOCKET_KEY,
      wsHost: process.env.WEBSOCKET_HOST,
      wsPort: process.env.WEBSOCKET_PORT,
      encrypted: true,
      disableStats: true,
    }],
  ],

authModule: When true it leverages from Nuxt auth module, this way you don't worry about how the auth is being handled, this will set up the token or any other authentication method internally unlike our manual set up.

connectOnLogin: When Nuxt auth module is authenticated it will allow you to connect your private channels when needed.


This is basically what you need to do if you are using the same technologies. Please let me know you comments or suggestions.

Discussion

pic
Editor guide
Collapse
mankarsandesh profile image
Sandesh Mankar

how to listen to the event in NUXT (SSR Mode). can you give one example? Thanks in Advance

Collapse
eichgi profile image
Hiram Author

I am afraid I haven't use the SSR Mode with nuxt, or at least I didn't know. But please share your resolution when you got it!

Collapse
mankarsandesh profile image
Sandesh Mankar

Yeah, I found Solutions for both modes.
follow my Repo.
Nuxt SSR mode: github.com/mankarsandesh/nuxt-sock...
Nuxt SPA mode: github.com/mankarsandesh/nuxt-sock...

Thanks

Thread Thread
eichgi profile image
Thread Thread
kp profile image
KP

@mankarsandesh thanks for sharing! by chance could you share the laravel side of this? An end to end example would be really helpful to me.

Thread Thread
eichgi profile image
Hiram Author

For backend channeling authentication you would have to specify that you are using Laravel sanctum like this, given I am using the api prefix I put this in routes/api.php:

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

And taking this route as example it should works:

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

I hope this is the answer you were looking for

Thread Thread
kp profile image
KP

@eichgi I’ll have to give it a go - thanks for responding!