Created
April 22, 2025 11:02
-
-
Save benlacey57/fee061255b85f22d015e22912c0fefa9 to your computer and use it in GitHub Desktop.
Laravel Socket.io
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
| For Laravel Socket.io implementation with authentication, here's a complete example: | |
| // SERVER SIDE (Laravel) | |
| // In your BroadcastServiceProvider.php | |
| public function boot() | |
| { | |
| Broadcast::routes(['middleware' => ['auth:api']]); | |
| require base_path('routes/channels.php'); | |
| } | |
| // In your .env file | |
| BROADCAST_DRIVER=socket.io | |
| SOCKET_IO_HOST=localhost | |
| SOCKET_IO_PORT=6001 | |
| // In config/broadcasting.php - add to the connections array | |
| 'socket.io' => [ | |
| 'driver' => 'socket.io', | |
| 'host' => env('SOCKET_IO_HOST', 'localhost'), | |
| 'port' => env('SOCKET_IO_PORT', 6001), | |
| 'options' => [ | |
| 'auth' => [ | |
| 'headers' => [ | |
| 'Authorization' => 'Bearer ' . auth()->user()->api_token, | |
| ], | |
| ], | |
| ], | |
| ], | |
| // CLIENT SIDE | |
| // In your JavaScript file | |
| import Echo from 'laravel-echo'; | |
| import io from 'socket.io-client'; | |
| window.io = io; | |
| window.Echo = new Echo({ | |
| broadcaster: 'socket.io', | |
| host: `${window.location.protocol}//${window.location.hostname}:6001`, | |
| auth: { | |
| headers: { | |
| Authorization: `Bearer ${userToken}`, // You need to pass your user token here | |
| Accept: 'application/json', | |
| }, | |
| }, | |
| }); | |
| // To listen to a channel: | |
| window.Echo.private(`user.${userId}`) | |
| .listen('UserEvent', (e) => { | |
| console.log(e); | |
| }); | |
| // For Socket.io server (typically in server.js) | |
| const server = require('http').Server(app); | |
| const io = require('socket.io')(server); | |
| const Redis = require('ioredis'); | |
| const redis = new Redis(); | |
| redis.subscribe('my-channel'); | |
| redis.on('message', (channel, message) => { | |
| message = JSON.parse(message); | |
| io.emit(channel + ':' + message.event, message.data); | |
| }); | |
| io.on('connection', (socket) => { | |
| // Authenticate the user | |
| const token = socket.handshake.query.token || socket.handshake.headers.authorization?.split(' ')[1]; | |
| if (!token) { | |
| socket.disconnect(); | |
| return; | |
| } | |
| // Verify token with your API | |
| axios.get('/api/user', { | |
| headers: { Authorization: `Bearer ${token}` } | |
| }) | |
| .then(response => { | |
| socket.user = response.data; | |
| console.log('Authenticated:', socket.user.name); | |
| }) | |
| .catch(error => { | |
| socket.disconnect(); | |
| }); | |
| }); | |
| server.listen(6001); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment