Skip to content

Instantly share code, notes, and snippets.

@jaygaha
Created May 1, 2023 08:29
Show Gist options
  • Save jaygaha/ed542edca17bbb2447ed83f0a54aa56a to your computer and use it in GitHub Desktop.
Save jaygaha/ed542edca17bbb2447ed83f0a54aa56a to your computer and use it in GitHub Desktop.
Laravel Echo With Nuxt 3

How to use Laravel Echo in Nuxt 3 consuming RESTful API

Laravel as backend in server and Nuxt 3 in frontend

Assuming that Laravel Websockets has been already set up in backend.

Laravel Echo has everything you need for a separate Nuxt 3 front-end application. Let’s install the package with pusher js.

npm i laravel-echo pusher-js

Plugins

Create plugin and save in plugins directory as echo.client.js

import Echo from 'laravel-echo'
import Pusher from 'pusher-js'
 
window.Pusher = Pusher
const token = useCookie('token')

export default defineNuxtPlugin(nuxtApp => {
    const echo = new Echo({
      broadcaster: 'pusher',
      key: 'same-key-as-server',
      wsHost: '127.0.0.1', // update according to backend server url
      authEndpoint: 'http://127.0.0.1/api/broadcasting/auth', // backend broadcasting auth url
      cluster: 'ap3',
      wsPort: 6001, // websocket port in server
      forceTLS: false,
      disableStats: true,
      auth: {
        headers: {
          authorization: 'Bearer ' + token.value,
        }
      }
  })
  
  return {
    provide: {
      echo
    }
  }
})

Usages

const { $echo } = useNuxtApp();

onMounted(() => {
  $echo.join('chat')
    .here()
    .joining()
    .leaving()
    .listen();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment