Created
September 29, 2023 14:58
-
-
Save maxcelos/4f26e1f8d93c2b9f7cdba5417cbbd18e to your computer and use it in GitHub Desktop.
Simple implementation of Laravel Echo in vanilla JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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