Creating An App Using Laravel WebSockets and NextJs (PART 2)

Pius Adams Ijachi
2 min readApr 4, 2022
still googled

So for this chapter, I assume you know how next js works, now so before we can listen to events on the frontend we need to install laravel echo

npm install --save-dev laravel-echo pusher-js

Now we need to configure echo to authenticate users (because we planning to listen to a private channel)

import Echo from "laravel-echo";const broadcastAuthInstance = axios.create({baseURL: 'http://localhost:8000/api/broadcasting/',// the auth routeheaders: {'Content-Type': 'application/json','Accept': 'application/json'}})const EchoConfig = () =>{window.Pusher = require('pusher-js');broadcastAuthInstance.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('token')}`;window.Echo = new Echo({broadcaster: 'pusher',key: "local",// same key used in the pusher key wsHost:"localhost",// host when you deploy would be your domainwsPort: 6001,// same portforceTLS: false, // force https to falsedisableStats: true, // don't send stats to pusher because we aren't using pusherauthorizer: (channel, option) => {return {authorize: (socketId, callback) => {broadcastAuthInstance.post('auth', {socket_id: socketId,channel_name: channel.name,}).then(response => {console.log(response)callback(false, response.data);}).catch(error => {callback(true, error);});}}}})}export default EchoConfig;

So now in a Driver component, we can

useEffect( () =>{
// get driver from local storage
let currentDriver = JSON.parse( localStorage.getItem('driver') );EchoConfig();// import the echo config to authenticate driver// LISTEN TO THE driver.{driverID} basically listen to the channel // we createdwindow.Echo.private(`driver.${currentDriver?.id}`).listen('DriverRequested', (e) => {
// listen to the DriverRequested event
console.log(e.request,'test');// console the message})return () =>{console.log('clean up...')}},[router])

Same happens to the User component

useEffect( () =>{let currentUser = JSON.parse(localStorage.getItem('user'))EchoConfig();window.Echo.private(`User.${currentUser.id}`).listen('UserRequestStatusUpdate', (e) => {console.log(e.message,'test');;})console.log('loading...')return () =>{console.log('clean up...')}},[router])

So with that our next js app can connect to the WebSocket channel and listen to the event.

I have a video demo but apparently can’t share it unless I have a youtube link or something...

anyways here is a demo I posted on LinkedIn

Thanks for reading here is a GitHub link to the repo

backend repo

nextjs repo

--

--