WebSocket: What it is and how to use it in modern web applications
WebSocket is a technology for real-time two-way communication between a client and a server. In the article, we will consider the principle of operation and implementation on JavaScript, Node.js and Laravel.
Igor Krivoshey
Development and DevOps specialist

WebSocket: What it is and how it works
WebSocket is a protocol that allows a persistent connection between a client and a server to exchange data in real time.
Unlike HTTP, where each request is separate, WebSocket works over a single long-lived connection.
Example: Frontend WebSocket (JavaScript)
const socket = new WebSocket('ws://localhost:3000');
socket.onopen = () => {
console.log('Підключено');
socket.send('Hello');
};
socket.onmessage = (event) => {
console.log('Повідомлення:', event.data);
};Example: WebSocket server on Node.js
npm install wsconst WebSocket = require('ws');
const server = new WebSocket.Server({ port: 3000 });Example: WebSocket in Laravel (PHP)
Laravel doesn't work with WebSockets out of the box, but it has a handy Broadcasting system.
The most popular options:
Laravel WebSockets (self-hosted)
Pusher (SaaS)
Consider the self-hosted option.
Step 1: Installing the package
composer require beyondcode/laravel-websocketsStep 2: Publish the configuration
php artisan vendor:publish --provider="BeyondCode\LaravelWebSockets\WebSocketsServiceProvider"Step 3: Start the server
php artisan websockets:serveStep 4: Creating an event (Event)
php artisan make:event MessageSentuse Illuminate\Broadcasting\Channel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class MessageSent implements ShouldBroadcast
{
public $message;
public function __construct($message)
{
$this->message = $message;
}
public function broadcastOn()
{
return new Channel('chat');
}
Step 5: Dispatch the event
event(new MessageSent('Привіт з Laravel'));Step 6: Connection on the frontend (Laravel Echo)
npm install laravel-echo pusher-jsimport Echo from "laravel-echo";
import Pusher from "pusher-js";
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'local',
wsHost: window.location.hostname,
wsPort: 6001,
forceTLS: false,
disableStats: true,
});When to use Laravel + WebSocket
This stack is ideal for:
chats in CRM
live notifications
admin panel
real-time updates of order statuses
Important nuances
Laravel uses Broadcasting, not "pure" WebSocket
a separate WebSocket server is required
for production, Redis is often added
WebSocket vs HTTP
Characteristic | HTTP | WebSocket |
|---|---|---|
Connection type | Question-answer | Permanent |
Bilaterality | No | Yes |
Delay | Higher | Lower |
Conclusion
WebSocket opens up possibilities for creating truly interactive web applications. In connection with Laravel, it allows you to quickly implement real-time functionality without complex low-level logic.
The main thing is to use it where it is really justified.
