Understanding authentication with websockets

Hello everybody,

I am trying to understand and solve an issue: I want to make use of Websockets in order to broadcast events from my backend (Laravel using Soketi) to my frontend (Nuxt3). For auth I am using nuxt-auth-sanctum (https://github.com/manchenkoff/nuxt-auth-sanctum)

Now here's what happens: Using this plugin (
echo.client.ts
):

export default defineNuxtPlugin(() => {
  window.pusher = Pusher
  const config = useRuntimeConfig().public
  const token = useCookie('XSRF-TOKEN')

  const echo = new Echo({
    broadcaster: 'pusher',
    key: config.pusherKey,
    wsHost: config.pusherHost,
    wsPort: config.pusherWsPort,
    wssPort: config.pusherWssPort,
    forceTLS: (config.pusherScheme ?? 'https') === 'https',
    enabledTransports: ['ws', 'wss'],
    cluster: config.pusherCluster,
    auth: {
      headers: {
        'X-XSRF-TOKEN': token.value
      }
    }
  })

  return {
    provide: {
      echo: echo
    }
  }
})


I indeed can subscribe to a channel like this:

onMounted(() => {
  $echo.private(`Order.${props.order.uuid}`).listen('.OrderShipped', () => {
    refresh()
  })
})


But if I try to subscribe to another channel in another compoent, I am getting logged out.

I am using routeRules to proxy requests to my backend, which I defined like this:

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  routeRules: {
    '/backend/auth/**': {
      proxy: {
        to: `${process.env.NUXT_BACKEND_URL}/auth/**`,
        headers: { accept: 'application/json' }
      }
    },
    '/broadcasting/auth': {
      proxy: `${process.env.NUXT_BACKEND_URL}/api/${process.env.NUXT_API_VERSION}/broadcasting/auth`,
      headers: { accept: 'application/json' }
    },
  },
})


Now I really don't have any idea, what's going wrong there. What I do see is that for some reason a new session is being created when I subscribe to two channels, which does not happen if I subscribe only to one.
GitHub
Nuxt module for Laravel Sanctum authentication. Contribute to manchenkoff/nuxt-auth-sanctum development by creating an account on GitHub.
Was this page helpful?