Skip to content

Instantly share code, notes, and snippets.

@maxcelos
Created September 29, 2023 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maxcelos/4f26e1f8d93c2b9f7cdba5417cbbd18e to your computer and use it in GitHub Desktop.
Save maxcelos/4f26e1f8d93c2b9f7cdba5417cbbd18e to your computer and use it in GitHub Desktop.
Simple implementation of Laravel Echo in vanilla JS
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
import axios from 'axios';
const token = 'your-access-token'
const authUrl = 'your-api-url/api/broadcasting/auth'
const pusherKey = 'your-pusher-key'
const pusherCluster = 'mt1'
const userId = 1
const privateChannel = 'App.Models.User.' + userId
const api = axios.create({
headers: {
"Authorization": `Bearer ${token}`
}
})
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: pusherKey,
cluster: pusherCluster,
forceTLS: true,
authorizer: (channel, options) => {
return {
authorize: (socketId, callback) => {
api.post(authUrl, {
socket_id: socketId,
channel_name: channel.name
})
.then(response => {
callback(null, response.data);
})
.catch(error => {
callback(error);
});
}
};
},
});
window.Echo.private(privateChannel)
.notification((notification) => {
console.log(notification);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment