Giter Club home page Giter Club logo

laravel-echo-module's Introduction

@nuxtjs/laravel-echo

npm version npm downloads Github Actions CI Codecov License

Laravel Echo for Nuxt 2

๐Ÿ“– Release Notes

Requirements

If you use the broadcaster pusher, you need to ensure that you have pusher-js installed:

yarn add pusher-js # or npm install pusher-js

If you use the broadcaster socket.io, you need to ensure that you have socket.io-client installed:

yarn add socket.io-client # or npm install socket.io-client

Setup

  1. Add @nuxtjs/laravel-echo dependency to your project
yarn add --dev @nuxtjs/laravel-echo # or npm install --save-dev @nuxtjs/laravel-echo
  1. Add @nuxtjs/laravel-echo to the buildModules section of nuxt.config.js
export default {
  buildModules: [
    // Simple usage
    '@nuxtjs/laravel-echo',

    // With options
    ['@nuxtjs/laravel-echo', { /* module options */ }]
  ]
}

โš ๏ธ If you are using Nuxt < v2.9 you have to install the module as a dependency (No --dev or --save-dev flags) and use modules section in nuxt.config.js instead of buildModules.

Using top level options

export default {
  buildModules: [
    '@nuxtjs/laravel-echo'
  ],
  echo: {
    /* module options */
  }
}

Options

broadcaster

  • Type: String
  • Default: 'null'

You can use 'pusher', 'socket.io' or 'null'.

See https://laravel.com/docs/broadcasting#driver-prerequisites

plugins

  • Type: Array
  • Default: null

If you have plugins that need to access $echo, you can use echo.plugins option.

Note: Plugins are pushed in client mode only (ssr: false).

nuxt.config.js

export default {
  buildModules: [
    '@nuxtjs/laravel-echo'
  ],
  echo: {
     plugins: [ '~/plugins/echo.js' ]
  }
}

plugins/echo.js

export default function ({ $echo }) {
  // Echo is available here
  console.log($echo)
}

authModule

  • Type: Boolean
  • Default: false

Integration with Auth Module.

connectOnLogin

  • Type: Boolean
  • Default: false

Connect the connector on login, if authModule is set true.

disconnectOnLogout

  • Type: Boolean
  • Default: false

Disconnect the connector on logout, if authModule is set true.

Usage

This module inject $echo to your project:

<template>
  <div>
    <h1>Orders</h1>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$echo.channel('orders')
      .listen('OrderShipped', (e) => {
          console.log(e.order.name);
      });
  }
}
</script>

License

MIT License

Copyright (c) Nuxt Community

laravel-echo-module's People

Contributors

harlan-zw avatar joaopedroas51 avatar renovate[bot] avatar ricardogobbosouza avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-echo-module's Issues

app.$auth is undefined

Hi guys, I'm trying to get this module working with the auth module, but unfortunatelly this doesn't work because in the file plugin.js@13 "app.$auth" is undefined and no auth header is returned.

This is my nuxt.config.js:

...
  modules: [
...
    '@nuxtjs/auth'
...
  ],
buildModules: [
...
    '@nuxtjs/laravel-echo'
...
  ],
  echo: {
    authModule: true,
    connectOnLogin: true,
    disconnectOnLogout: true,
    broadcaster: 'socket.io',
    host: process.env.LARAVEL_ECHO_HOST
  },
...

Working on localhost, but not on production

Hello,

Everything is working perfectly fine on local machine, but on remove server $echo is undefined TypeError: Cannot read property 'private' of undefined

nuxt: 2.0.0,
laravel-echo: 1.1.0

modules: [
    '@nuxtjs/laravel-echo',
],
echo: {
    broadcaster: 'pusher',
    authModule: true,
    connectOnLogin: true,
    disconnectOnLogout: true,
    authEndpoint: process.env.API_BASE_URL + '/api/broadcasting/auth',
    key: process.env.PUSHER_APP_KEY,
    cluster: process.env.PUSHER_APP_CLUSTER,
    forceTLS: true,
    encrypted: process.env.PUSHER_APP_ENCRYPTED
}
mounted() {
    console.log(this.$echo) // TypeError: Cannot read property 'private' of undefined
}

Dones anyone have idea how to solve this?

Thanks

Wrong request body: Form Data instead of JSON - private channels

Hey,

I am working on a little app where I am using NuxtJS with the laravel echo package for the frontend and Laravel8 with the LaravelWebsockets package for the backend. I am trying to make it work with private channels and passport in Laravel.

I've noticed something really strange that I can't really change or I don't know how to do that.

It looks like Laravel Echo package is making the request with FORM data instead of JSON body which I need and I have no clue if and how I could change it.

When I am trying to subscribe to a private channel(pusher as a broadcaster) echo makes a request to brodcasting/auth endpoint which is fine. However, the data in that request is sent as form data and not as JSON body.

I've made a little plugin in nuxtjs to add headers and stuff so I tried it like this:

export default function ({ $echo, $auth}) {
  console.log($echo)

  let authData = {
    headers: {
      // Authorization: 'Bearer 1c2d3a31dd0c5e1933c609ffce1ef4e3'
      Authorization: $auth.strategy.token.get(),
      // Accept: 'application/json',
      "X-Requested-With": 'XMLHttpRequest',
      "Content-Type": 'application/json'
    },
  };

  $echo.connector.pusher.config.auth = authData;
  $echo.connector._defaultOptions.auth = authData;
  $echo.connector.options.auth = authData;
  $echo.options.auth = authData;
  // $echo.options.auth = authData;
}

My headers are added (although it seems like it is hardcoded in echo package to add application/x-www-form-urlencoded header).

As a result in my Laravel I am getting 403 error and when I traced the code back to where it breaks the data from request is missing. It is because Laravel at this points expects JSON body and it is not there.

My question is - can I somehow make Echo to send the application/json body? Maybe I am misunderstanding the whole thing?

Is there some other way to make this package for Nuxt to work nicely with passport?

Problem with connectors and authModule

package.json:

"@nuxtjs/laravel-echo": "^2.0.0-alpha.5",
"nuxt": "^2.14.12",
"@nuxtjs/auth-next": "5.0.0-1613647907.37b1156",
"pusher-js": "^7.0.3",

nuxt.config.js:

buildModules: [
    ...
    '@nuxtjs/laravel-echo',
  ],
modules: [
    ...
    '@nuxtjs/auth-next',
  ],
echo: {
    ...
    broadcaster: 'pusher',
    authModule: true,
}

My connector is set to NullConnector when I set authModule to true, But when I set it back to false, it's a PusherConnector again.
Any idea?

Couldn't listen from pusher.

Hi I am struggling to connect laravel-echo with pusher. I am broadcasting data from a laravel backend but in nuxt I couldn't listen to that data.

I am confused if I did some wrong.

Here is my nuxt.config.js configuration

buildModules: [
    // ....
    "@nuxtjs/laravel-echo",
],


echo: {
    broadcaster: "pusher",
    key: "xxxxxxxxxxxxxxxxxxxxxxxxx",
    cluster: "mt1",
    plugins: ["~/plugins/echo.js"],
    // auth
    authModule: true,
    connectOnLogin: true,
    disconnectOnLogout: false,
}

In one point of debugging, I tried to listen to data triggered by pusher Event Creator with channel name my-channel and event name my-event

image

And then I tried to listen this event from a component like this.

  mounted() {
    this.$echo.channel("my-channel").listen("my-event", (e) => {
      console.log(e);
    });
}

But got nothing

Please help me to figure out the actual problem. I am sure I am doing some wrong or bad practice here but couldn't manage to solve that.

How to use custom autorization without nuxt/auth module?

Hi

Thanks for your good package, I'm using laravel as backend API (with passport package) and I have some issues with your package, please help me to solve this. let me explain it to you:

I have laravel as backend in the localhost:8000 domain and have a nuxtJS project in the localhost:3000. I'm making a login request from nuxt application to laravel with Axios and save user tokens in cookies.

now when I want to subscribe to private or presence channel I get 401 and it's because of that I cannot set the header for broadcasting/auth endpoint. remember I saved user token in browser cookies.

in nuxt.config.js file i have these options for echo:

echo: {
    broadcaster: 'pusher',
    host: '127.0.0.1:6001',
    wsHost: '127.0.0.1',
    wsPort: 6001,
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: 'mt1',
    forceTLS: false,
    encrypted: false,
    disableStats: true,
    authEndpoint: 'http://127.0.0.1:8000/broadcasting/auth',
    auth: {
       headers: {
            Authorization: `Bearer ${cookies.get('user_token')}`           // i'm using js-cookie package to works with cookies
       }
    }
  },

And in Laravel:

in BroadcastServiceProvider:

 public function boot()
    {
        Broadcast::routes(['middleware' => 'auth:api']);

        require base_path('routes/channels.php');
    }

in my event file:

public function broadcastOn()
    {
        return new PresenceChannel('user.messages.chat.' . $this->user_id);
    }

in controller file:

broadcast(new ApplicationChatMessage(json_encode($message), auth('api')->id()))->toOthers();

in routes/channel.php:

Broadcast::channel(
    'user.messages.{id}', //parameter 1
    function ($user, $id) {      //parameter 2
        return (int)$user->id === (int)$id;
    }); 

But it's RETURN 401.

are you can help me to solve this issue?

Echo wont connect after page refresh

In order to get echo working after a page refresh I have to do this:

this.$echo.options.broadcaster = this.$echo.config.broadcaster
await this.$echo.connect()

it works when the user logs in, but after a refresh it stops and options.broadcaster is null, and connect isnt run again.

i am on version alpha5 with the latest auth-next, my config is:

  echo: {
    broadcaster: 'pusher',
    key: process.env.PUSHER_APP_KEY,
    cluster: process.env.PUSHER_APP_CLUSTER,
    authEndpoint: `${process.env.API_URL}/broadcasting/auth`,
    encrypted: true,
    authModule: true,
    connectOnLogin: true,
    disconnectOnLogout: true,
  },

Broadcasting with socket.io not listening

I was working about 2 days to install this package.
I set up my laravel in docker and installed a redis container. Also installed predis on composer.

in nuxt side I run this commands:

npm install socket.io-client
npm install --save-dev @nuxtjs/laravel-echo

my files looks like this

nuxt.config.js
buildModules: [ // https://go.nuxtjs.dev/vuetify '@nuxtjs/vuetify', ['@nuxtjs/laravel-echo', { broadcaster: 'socket.io', host: 'backend.localhost', transports: ['websocket', 'polling'], }] ],

in any vue component
this.$echo.channel('aChannel') .listen("TestEvent", (e) => { console.log(e); });

When I inspect on chrome console, ws is connect to server. But when i fire an event on laravel, nuxt side was not listening.

Also when I inspect socket properties, connect property was false.

However, when I changed socket.io-client version to 2.4.0 it worked...

"socket.io-client": "2.4.0"

I dont know why but may you fix this problem.

[Issue] Usage in plugin

Hi there is currently a issue with importing and using the echo module in a plugin, a temporary workaround suggested by @ricardogobbosouza is to use the hook builder:extendPlugins.
A code example of this would look like the following:

// nuxt.config.js
modules: [
  '@nuxtjs/laravel-echo',

  { handler: function() {
    this.nuxt.hook('builder:extendPlugins', (plugins) => {
      plugins.push('~/plugins/extend-echo.js')
    })
  }}
]

// ~/plugins/extend-echo.js
export default function ({ $echo }) {
  // Echo should be defined here  
  console.log($echo)
}

TypeError: io is not a function

> client.js?06a0:103 TypeError: io is not a function
> at SocketIoConnector.connect (echo.js?5638:1149)
> at new Connector (echo.js?5638:142)
> at SocketIoConnector.eval (echo.js?5638:111)
> at new SocketIoConnector (echo.js?5638:1130)
> at Echo.connect (echo.js?5638:1414)
> at new Echo (echo.js?5638:1388)
> at eval (echo.js?1380:19)
> at _callee2$ (index.js?f26e:83)
> at tryCatch (runtime.js?96cf:63)
> at Generator.invoke [as _invoke] (runtime.js?96cf:294)
buildModules: [
  '@nuxtjs/laravel-echo'
],

echo: {
  broadcaster: 'socket.io',
  host: 'http://127.0.0.1:6500',
},

Already ran,

npm install --save-dev @nuxtjs/laravel-echo
npm install socket.io-client

Module overwrites custom Axios configuration

I've encountered problem where this module will try to overwrite my Axios configuration.

I am using @nuxtjs/composition-api alongside with typed-vuex, so in order to be able to use Axios in my store/index.ts, i need to create custom accessor (axios/accessor.ts):

import { Plugin } from '@nuxt/types';
import { AxiosRequestConfig } from 'axios';
import { axiosOnRequestConfiguration, ContextWithAxios } from '~/plugins/third-party/axios';
import { initializeAxios } from '~/services/common/axios';

const accessor: Plugin = ({ $axios, $accessor } : ContextWithAxios) => {
    initializeAxios($axios);

    $axios.onRequest((config: AxiosRequestConfig) => {
        axiosOnRequestConfiguration($accessor, config);
    });

};

export default accessor;

And here is the axios/index.ts:

import { Context } from '@nuxt/types';
import { NuxtAxiosInstance } from '@nuxtjs/axios';
import { AxiosRequestConfig } from 'axios';
import { isDefinedAndNotNull, isUndefinedOrNull } from '~/utilities/helpers';
import { accessorType } from '@/source/store';

export interface ContextWithAxios extends Context {
    $axios: NuxtAxiosInstance;
}

export const axiosOnRequestConfiguration = ($accessor: typeof accessorType, config: AxiosRequestConfig) => {
    config.headers.common['Content-Type'] = 'application/json';
    config.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    config.headers.common['X-Requested-Time'] = new Date().getTime();
    let currentRequestUrl = config.url;
    if (currentRequestUrl !== undefined) {
        if (currentRequestUrl.startsWith('console/')) {
            if (isDefinedAndNotNull($accessor.console.token)) {
                config.headers.common.Authorization = `${$accessor.console.token_type} ${$accessor.console.token}`;
            }
        }
    }

    if (isUndefinedOrNull(config.headers.common.Authorization)) {
        if (isDefinedAndNotNull($accessor.account.token)) {
            config.headers.common.Authorization = `${$accessor.account.token_type} ${$accessor.account.token}`;
        }
    }
}

export default function ({
    $axios,
    $accessor
} : ContextWithAxios) {
    $axios.onRequest((config: AxiosRequestConfig) => {
        axiosOnRequestConfiguration($accessor, config);
    });
}

$accessor in this case is the typed-vuex accessor and the store/index.ts looks like this:

import { GetterTree, ActionTree, MutationTree } from 'vuex';
import { getAccessorType } from 'typed-vuex';

export const state = () => ({});
export type RootState = ReturnType<typeof state>;

export const getters: GetterTree<RootState, RootState> = {};

export const mutations: MutationTree<RootState> = {};

export const actions: ActionTree<RootState, RootState> = {};

import * as account from '~/store/account';
import * as application from '~/store/application';
import * as console from '~/store/console';

export const accessorType = getAccessorType({
    state,
    getters,
    mutations,
    actions,
    modules: {
        application,
        account,
        console,
    },
});

So whenever i refresh page, i am getting all sorts of errors as my Axios instance is now overwritten by this module.

image

Can't get event to fire

Hi there, I'm using 1.1.0 version of the module.

I went through the config and got it all as per instructions, but it seems that this.$echo is not listening for the events.

I can see the messages being received in Dev Tools but the listen code is not responding to them.
image

Basic example from the documentation:

mounted () { this.$echo.channel('orders') .listen('OrderShipped', (e) => { console.log(e.order.name) }) },
Does not logs the error. I've tried different changing it to just console.log(e) to see if I'll get any data but it doesn't provide anything.

What am I missing here?

NuxtJs: Runtime public config (or runtime private config)

Hi.

I noticed this repo hasn't been updated in a while, and it could benefit from quite a lot of new features/enhancements. Are you planning to maintain this repo or what's the plan going forward?

One issue that I'm facing right now, is trying to inject variables at runtime config (rather than build), in a NuxtJS installation with ssr: false and target: server. (especially the pusher key, e.g. key: process.env.PUSHER_APP_KEY)

Either I'm not doing something right, or, from the looks of it, this is not supported.

Any hints would be really appreciated.

this.$echo not exists

well, I did everything as insctructed, but everytime, I try to usethis.$echo.channelIt keep saying, that I am trying to call channel on null. I spent 6h tried to get what went wrong, but still no result. Maybe there is somthing missed in instruction?

Using private channels

Hey,

I couldn't find anything about using private channels, is it supported.

According to Laravel Docs, in Echo we can do something like :
Echo.private('App.User.${userId}') .notification((notification) => { console.log(notification.type); });

But when I use
this.$echo.private...something similar
It isn't subscribing to the Private Channel.

What am I missing here?

Individual channel authentication not triggered

Hi all.

Im currently working on implementing chat into our application - Im using Laravel-echo together with Pusher. I have SPA and use JWT authentication via API endpoint.

The authentication is working, but when the user is authenticated on the top level, no individual channel authentication is done. So any and every authenticated users can subscribe to every chat channel and recieve their messages ๐Ÿ‘Ž

echo: {
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: process.env.NODE_ENV === 'production',
    authModule: true,
    authEndpoint: `${process.env.API_URL}/broadcasting/auth`,
    connectOnLogin: true,
    disconnectOnLogout: true,
    auth: {
      headers: {
        'X-AUTH-TOKEN': process.env.API_AUTH_TOKEN
      }
    }
  },

As you can see i have added a custom endpoint for authentication from my API. This is working and im getting a response from my custom authentication with the h256 string plus some user information as i would want to use presence channels.

How can I set up that further authentication is needed e.g. with BroadcastServiceProvider > Broadcast::routes(['middleware' => 'auth:api']) ?
Is it perhaps possible to do custom connection to a channel and specify another auth endpoint ? Because at the moment I am able to completely disable the BroadcastServiceProvider in the Backend and im still authenticated via the api/broadcasting/auth endpoint, and then able to subscribe to all channels as I please.

require('pusher-js/with-encryption')

Im currently working with nuxt/laravel-echo. I want to use encrypted channels and can see that it is not included in the basic pusher.js and you have to explicitly implement Pusher with it. Where can I change which library is used ? Here is my nuxt.config.js

echo: {
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    forceTLS: process.env.NODE_ENV === 'production',
    authModule: true,
    authEndpoint: `${process.env.API_URL}/broadcasting/auth`,
    connectOnLogin: true,
    disconnectOnLogout: true,
    encrypted: true,
    encryptionMasterKeyBase64: process.env.MIX_PUSHER_ENC_MASTER_KEY,
    auth: {
      headers: {
        'X-AUTH-TOKEN': process.env.API_AUTH_TOKEN
      }
    }
  },

And in my component:

this.channel = this.$echo.encryptedPrivate(`chat.${this.chat.id}`)
        .listen('chat.message.new', ({ chatMessage }) => {
          this.localMessages.push(chatMessage)
        })
        .listen('chat.message.update', ({ chatMessage }) => {
          this.updateArray(chatMessage)
        })
        .listen('chat.message.delete', ({ chatMessage }) => {
          this.updateArray(chatMessage)
        })

But i get the following exception:
Tried to subscribe to a private-encrypted- channel but no nacl implementation available

By changing this in echo.js fixes it.

import Echo from 'laravel-echo'

//window.Pusher = require('pusher-js')
window.Pusher = require('pusher-js/with-encryption')

function getHeaders ({ app }) {
  const headers = {}

  if (app.$auth) {
    const strategy = app.$auth.strategy
    const tokenName = strategy.options.tokenName || 'Authorization'
    const token = app.$auth.getToken(strategy.name)

    if (token) {
      headers[tokenName] = token
    }
  }

  return headers
}

This should of course take into account the encrypted bool in the config

Access to echo instance on auth scheme

Hi there,

I have this in my nuxt.config.js

buildModules: [
        // Doc: https://github.com/nuxt-community/eslint-module
        '@nuxtjs/eslint-module',

        // Doc: https://github.com/nuxt-community/nuxt-tailwindcss
        '@nuxtjs/tailwindcss',
        '@nuxtjs/laravel-echo',
        // Doc: https://github.com/nuxt-community/dotenv-module
        ['@nuxtjs/dotenv'],
 ],

and outside of build module

    echo: {
        authModule: true,
        connectOnLogin: true,
        disconnectOnLogout: true,
        broadcaster: 'pusher',
        key: process.env.PUSHER_KEY,
        authEndpoint: process.env.SOCKET_HOST + '/broadcasting/auth',
        cluster: 'eu',
        plugins: ['~/plugins/echo.js'],
    },

and auth scheme like

    auth: {
        redirect: {
            login: '/login',
            logout: '/login',
            callback: false,
            home: false,
        },
        strategies: {
            myScheme: {
                _scheme: '~/schemes/myScheme',
                endpoints: {
                    login: {
                        url: process.env.API_URL + '/login-end-oint',
                        method: 'post',
                        propertyName: 'access_token',
                    },
                    logout: {
                        url: process.env.API_URL + '/logout',
                        method: 'delete',
                    },
                    user: {
                        url:
                            process.env.API_URL +
                            '/user/profile',
                        method: 'get',
                        propertyName: 'data',
                    },
                },
            },
        },
    },

and my echo.js in plugins

export default function ({ $echo, app }) {

    if (
        app.$auth &&
        app.$auth.$state.hasOwnProperty('user') &&
        app.$auth.$state.user &&
        app.$auth.$state.user.hasOwnProperty('id')
    ) {
        const id= app.$auth.$state.user.id
        $echo
            .private('my-notifications.' + id)
            .listen('.TestEvent', (e) => {
                console.log('event triggered')
                console.log(e.entity)
            })
    }
}

So the issue here, is when I'm logging in, this doesn't make connection to that channel automatically, and works only when I'm doing refresh in browser.

So basically authorization is not happening when I'm logging in.

Any hints, how can I do that?

Thanks

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/setup-node v2
  • actions/checkout v2
  • actions/cache v2
  • codecov/codecov-action v1
npm
package.json
  • defu ^3.2.2
  • laravel-echo ^1.10.0

  • Check this box to trigger a request for Renovate to run again on this repository

Refreshed tokens not applied

If socket has already connected through a valid token and token gets refresh after a while, the library still using the old token and that will cause 401 subscription_error on subscribe requests!
I'm experiencing this on socket.io adapter.

Any ideas on how solve this?

nuxtjs ssr problem

im using nuxt/auth with cookie schemes
is this works with this schemes ?
i googles a lot and only thing i found joining with bearer token, can you tell me an example of joining private channel with this schemes ?
thanks alot

Can't get event fired from backend

I'm trying to receive events from Laravel Backend through Redis. Using laravel-echo-server start i can see the events firing from Backend but i am unable to receive on my nuxt application.

As title said when i open the page the socket connection went fine but after that nothing happens. If i'm not wrong in the Chrome Devtools Network tab i should see pooling requests, right?

I'm using socket-io.

Thanks in advance.

Issues while trying to connect Presence/Private Channels with authModule (Sanctum & Soketi)

I am using Soketi as the server to receive requests. It seems that public channels work fine, but when I enable auth for presence/private channels, I end up running into the issue below. I am using Sanctum for authentication, I've enabled the required configuration for Laravel for Sanctum to work with the authEndpoint below.

Also I am using Cookie based Sessions, not tokens

nuxt.config.js

buildModules: [
  ...
  '@nuxtjs/laravel-echo',
],

echo: {
    broadcaster: 'pusher',
    authEndpoint : 'http://127.0.0.1:8000/api/broadcasting/auth',
    authModule: true,
    wsHost: '127.0.0.1',
    wsPort: 6001,
    key: 'my_key',
    encrypted: true,
    enableLogging: false,
    connectOnLogin: false,
    disconnectOnLogout: false,
    disableStats: false,
    forceTLS: false
  }

Error:

[x] POST http://127.0.0.1:8000/api/broadcasting/auth 401 (Unauthorized)

Ready for NuxtJS3?

Hi there,

I tested this module in NuxtJS3, which did not work out, so I guess it's not yet ready for NuxtJS3.

But if I'm wrong, I really appreciate examples or a documentation showing the usage of this module in nuxt3.

Thanks :-)

Create hooks

Trigger an action before and after the connect and disconnect methods.

whisper and listenForWhisper

I was able to publish from client a whisper, but other client does not pick that up.

Can anybody share working example?

I'am not sure if docker is failing here, because I am able to broadcast messages from backend and this is received on all clients.

As well as whisper made from frontend was picked up in console output and in laravel websocket dashboard.

And yes, enable_client_messages is set to true.

I've tried many different ways how to listen to the event - channel().listenForWhisper(), private().listenForWhisper() and what not, can't remember already...

How to configure using custom pusher server ?

Here's my configuration. I can't find on the docs on how to configure key, host, port and auth endpoint.

const config = {
  broadcaster: 'pusher',
  key: process.env.PUSHER_APP_KEY,
  wssHost: process.env.PUSHER_APP_HOST,
  wssPort: process.env.PUSHER_APP_PORT,
  authEndpoint: process.env.WS_AUTH_ENDPOINT,
  disableStats: true,
  auth: {
    headers: {
      Authorization: '',
      Accept: 'application/json'
    }
  }
}

v2.0.0-alpha.1 with laravel sanctum is broken

Hi @ricardogobbosouza I have these package versions

dependencies:

  1. @nuxtjs/auth-next 5.0.0-1613647907.37b1156
  2. nuxt ^v2.15.4
  3. pusher-js ^7.0.3

devDependencies

  1. @nuxtjs/laravel-echo ^2.0.0-alpha.1

with the following nuxt config

buildModules: [
  ...
  '@nuxtjs/laravel-echo',
],

echo: {
    authEndpoint: '/laravel/broadcasting/auth',
    authModule: true,
    broadcaster: 'pusher',
    cluster: 'ap1',
    connectOnLogin: true,
    disconnectOnLogout: true,
    encrypted: true,
    forceTLS: true,
    key: process.env.PUSHER_APP_KEY,
},

modules: [
    ...
    '@nuxtjs/auth-next',
],

As you suggest to install v2.0.0-alpha.1 on recent issue #47 along with nuxt auth next laravel sanctum strategy, it resulted ReferenceError "location is not defined" on this line:

headers.referer = location.origin

Make this package use my Axios instance

Hi,

So I have this nuxt module installed along with nuxt's axios module.
My axios instance is currently having a X-XSRF-TOKEN header configured inside it (because Laravel Sanctum) and I need this module to use the axios instance so that I can authenticate my SPA with Laravel's Broadcasting.

Nuxt 3 Support

Hi ๐Ÿ‘‹ It looks like this module hasn't been updated for Nuxt 3. In an effort to improve the developer experience of modules, I've updated the module to clarify that it only supports Nuxt 2.

If Nuxt 3 support is added it will be moved to the https://github.com/nuxt-modules organisation.

@ricardogobbosouza Is Nuxt 3 support something you have planned? If not, perhaps we can archive this module?

Please let us know and thanks for your work!

Request Delay before echo.connect()

Hello

Thank you for your project.

Please add the delay time option before echo.connect()
because when i need start socket.io after page load completed

Thank.

Not receiving any data from echo

Hi, I'm having trouble getting any data to come through with this package and wonder whether it's working as intended. I've got Laravel Websockets set up (the package) and have my websocket server running and can see in the console that it is receiving data, but I'm not seeing any data coming through my channel to my Nuxt JS project.

/*
** Echo config
*/
echo: {
  broadcaster: 'pusher',
  key: 'websocketkey',
  host: 'http://localhost:6001',
  plugins: [ '~/plugins/echo.js' ],
},

In my web page, I've got:

this.$echo.channel('agents')
        .listen('AgentStats', (e) => {
            console.log(e);
        });
    }

My event channel is called agents, it's on a private channel, and the event is called AgentStats, but I see no data logged in my console log.

window is not defined

file: nuxt.config.js

  echo: {
...
    broadcaster: 'socket.io',
...
  }

It causes a "window is not defined" error at ../.nuxt/echo.js

Invalid token receipt when used with @nuxtjs/auth-next

Hello, when using @nuxtjs/auth-next, getting a token does not work. To make this work, you need to make changes to laravel-echo/lib/plugin.js on line 16.

Replace
const token = app.$auth.getToken(strategy.name)
with
const token = app.$auth.token.get(strategy.name)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.