Modern web applications often need to exchange data between a client and a server in real time. Whether you’re building a chat application, live notifications, online gaming platform, stock dashboard, or collaborative application, users expect information to update without constantly refreshing the page.
This is where WebSocket technology becomes useful.
But what is WebSocket, and how does it work?
WebSocket is a communication protocol that provides a persistent, two-way connection between a client and a server. Unlike traditional HTTP communication, where the client usually sends a request before receiving a response, WebSocket allows both sides to send messages whenever they need to.
In this guide, we’ll explain how WebSocket works, how it differs from HTTP, where it is used, its advantages and disadvantages, and how to create a simple WebSocket application.
What Is WebSocket?
WebSocket is a network communication protocol designed for real-time, bidirectional communication between a client and a server.
A WebSocket connection allows:
- Client → Server communication
- Server → Client communication
- Real-time data transfer
- Persistent connections
- Low-latency communication
Once a WebSocket connection is established, the server can send data to the client without waiting for a new request.
A simplified architecture looks like this:
Client
|
| WebSocket Connection
|
v
Server
|
| Real-Time Messages
|
v
Client
This makes WebSockets particularly useful when applications need continuous communication.
How Does WebSocket Work?
A WebSocket connection generally starts as an HTTP request.
The client sends a request asking the server to upgrade the connection from HTTP to WebSocket.
This process is known as the WebSocket handshake.
The communication flow looks like:
Client
|
| HTTP Upgrade Request
↓
Server
|
| 101 Switching Protocols
↓
WebSocket Connection Established
|
↓
Bidirectional Communication
Once the handshake is successful, the connection changes from HTTP communication to a persistent WebSocket connection.
The client and server can then send messages to each other independently.
What Is a WebSocket Connection?
A normal HTTP request generally follows this pattern:
Client → Request → Server
Client ← Response ← Server
With WebSocket:
Client ↔ Server
The connection remains open, allowing both sides to communicate whenever necessary.
For example, in a chat application:
User A → Message → Server
↓
WebSocket
↓
User B
The server doesn’t need to wait for User B to request new messages.
It can immediately send the message through the existing WebSocket connection.
WebSocket vs HTTP
Understanding the difference between WebSocket and HTTP is important.
| Feature | HTTP | WebSocket |
|---|---|---|
| Communication | Request-response | Bidirectional |
| Connection | Typically request-based | Persistent |
| Server can initiate message | Usually requires a new client request | Yes |
| Real-time communication | Requires additional techniques | Built in |
| Connection overhead | Higher for repeated requests | Lower after connection |
| Best for | APIs, websites, normal requests | Real-time applications |
HTTP is still the right choice for many applications.
You don’t need WebSockets simply because an application has dynamic data.
WebSockets are most useful when the server needs to push updates to clients in real time or when both sides need frequent communication.
WebSocket Handshake
Before WebSocket communication begins, the client and server perform a handshake.
A browser can initiate the connection using JavaScript:
const socket = new WebSocket("wss://example.com/socket");
The browser initially sends an HTTP request containing headers that indicate it wants to upgrade the connection.
Conceptually:
GET /socket HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
If the server supports WebSockets, it responds with a successful protocol upgrade.
After that, the connection is treated as a WebSocket connection rather than a normal HTTP request.
ws:// vs wss://
WebSocket URLs use two common schemes:
ws://
wss://
ws://
ws:// is the unencrypted WebSocket protocol.
Example:
const socket = new WebSocket("ws://localhost:8080");
It is generally suitable for local development or environments where encryption is not required.
wss://
wss:// is the secure version of WebSocket.
Example:
const socket = new WebSocket("wss://example.com/socket");
It uses encryption through TLS, similar to how HTTPS secures HTTP.
For production applications, wss:// should generally be used.
WebSocket Events in JavaScript
Browsers provide a built-in WebSocket API.
You can create a connection like this:
const socket = new WebSocket("ws://localhost:8080");
You can then listen for important events.
Connection Open
socket.onopen = () => {
console.log("WebSocket connection established");
};
This event runs when the connection has successfully opened.
Receiving a Message
socket.onmessage = (event) => {
console.log("Message:", event.data);
};
This event runs when the server sends a message.
Handling Errors
socket.onerror = (error) => {
console.error("WebSocket error:", error);
};
This allows you to handle connection errors.
Connection Closed
socket.onclose = () => {
console.log("WebSocket connection closed");
};
This runs when the WebSocket connection is closed.
Sending Messages With WebSocket
The client can send data to the server using the send() method.
socket.send("Hello Server");
You can also send JSON data.
socket.send(JSON.stringify({
type: "message",
text: "Hello Server"
}));
The server can receive and process this message.
A common pattern for real-time applications is to exchange JSON messages.
For example:
{
"type": "chat_message",
"userId": 123,
"message": "Hello!"
}
Building a Simple WebSocket Client
Here is a basic browser example:
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Example</title>
</head>
<body>
<button id="sendButton">Send Message</button>
<script>
const socket = new WebSocket("ws://localhost:8080");
socket.onopen = () => {
console.log("Connected to server");
};
socket.onmessage = (event) => {
console.log("Server:", event.data);
};
socket.onclose = () => {
console.log("Connection closed");
};
document.getElementById("sendButton").addEventListener("click", () => {
socket.send("Hello from browser!");
});
</script>
</body>
</html>
When the page connects to the WebSocket server, it can send and receive messages without making separate HTTP requests for every message.
Creating a WebSocket Server With Node.js
Node.js is commonly used for WebSocket applications.
One popular library is ws.
First, install it:
npm install ws
Then create a simple WebSocket server:
const WebSocket = require("ws");
const server = new WebSocket.Server({
port: 8080
});
server.on("connection", (socket) => {
console.log("Client connected");
socket.send("Welcome to the WebSocket server!");
socket.on("message", (message) => {
console.log("Received:", message.toString());
socket.send(`Server received: ${message}`);
});
socket.on("close", () => {
console.log("Client disconnected");
});
});
Now you have a basic WebSocket server that can accept connections and exchange messages with clients.
WebSocket Example: Real-Time Chat
A chat application is one of the most common WebSocket use cases.
Without WebSockets, a basic implementation might repeatedly request new messages:
Client → GET messages
Server → Messages
Client → GET messages
Server → Messages
Client → GET messages
Server → Messages
This is similar to polling.
With WebSockets:
Client ↔ WebSocket Server
The server can immediately send a new message when another user sends one.
For example:
User A
|
| "Hello!"
↓
WebSocket Server
|
| Real-time message
↓
User B
This creates a much more responsive experience.
WebSocket vs Polling
Before WebSockets became widely used, applications often relied on polling to retrieve updates.
Polling
The client repeatedly sends requests:
Client → Server: Any new data?
Server → Client: No
Client → Server: Any new data?
Server → Client: No
Client → Server: Any new data?
Server → Client: Yes
This can generate unnecessary requests.
WebSocket
With WebSockets:
Client ↔ Server
The server can send data immediately when something changes.
This makes WebSockets more efficient for many real-time communication scenarios.
WebSocket vs Long Polling
Long polling is another technique for creating near-real-time applications.
With long polling, the client sends a request and the server keeps it open until new data becomes available or a timeout occurs.
After receiving a response, the client makes another request.
WebSockets are different because they maintain a persistent connection that supports communication in both directions.
| Feature | Long Polling | WebSocket |
|---|---|---|
| Persistent connection | No | Yes |
| Bidirectional communication | Limited | Yes |
| Real-time capability | Good | Excellent |
| Repeated HTTP requests | Yes | No after upgrade |
| Best use case | Compatibility/fallback | Real-time applications |
Common WebSocket Use Cases
WebSockets are useful whenever applications need frequent, low-latency communication.
1. Chat Applications
Examples include:
- Customer support chat
- Team messaging
- Social messaging
- Online communities
2. Live Notifications
WebSockets can deliver notifications instantly.
For example:
New Order Received
Payment Completed
New Message
Booking Confirmed
The user doesn’t need to refresh the page.
3. Online Gaming
Multiplayer games need frequent communication between players and servers.
WebSockets can help synchronize:
- Player positions
- Game state
- Scores
- Events
- Player actions
4. Live Dashboards
WebSockets are useful for dashboards that display constantly changing information.
Examples include:
- Stock market dashboards
- Monitoring systems
- Analytics dashboards
- Server monitoring
- Delivery tracking
5. Collaborative Applications
Applications such as collaborative editors can use WebSockets to synchronize changes between users.
For example:
User A edits document
↓
WebSocket Server
↓
User B receives update
Advantages of WebSockets
Real-Time Communication
The server can send data to connected clients immediately.
Two-Way Communication
Both client and server can send messages.
Persistent Connection
The connection remains open instead of creating a new request for every message.
Low Latency
Once the connection is established, messages can be exchanged efficiently.
Efficient for Frequent Updates
WebSockets are particularly useful when an application needs frequent updates.
Disadvantages of WebSockets
WebSockets aren’t the right solution for every application.
More Complex Infrastructure
Managing persistent connections can be more complicated than handling normal HTTP requests.
Connection Management
Applications need to handle:
- Connection failures
- Reconnection
- Disconnections
- Timeouts
- Authentication
- Server restarts
Scaling Challenges
When you have many connected users, maintaining large numbers of persistent connections requires careful infrastructure planning.
Not Necessary for Every Application
If an application only needs occasional data retrieval, a normal REST API may be simpler and more appropriate.
WebSocket Security
Security is extremely important when building WebSocket applications.
Use Secure Connections
Use:
wss://
instead of:
ws://
for production communication.
Authenticate Users
Your WebSocket server should verify that users are authorized to establish connections and access specific data.
Validate Messages
Never blindly trust data received from a client.
Validate incoming messages before processing them.
For example:
{
"type": "message",
"content": "Hello"
}
Your server should verify that the message structure and content are valid.
Handle Authorization
Authentication determines who the user is.
Authorization determines what that user is allowed to do.
A WebSocket application should implement both where required.
WebSocket Scaling
Scaling a WebSocket application is different from scaling a traditional REST API.
With REST APIs, requests are usually independent.
With WebSockets, users maintain persistent connections.
For example:
User 1 ─────┐
User 2 ─────┤
User 3 ─────┤
User 4 ─────┼── WebSocket Servers
User 5 ─────┤
User 6 ─────┘
Large applications may need:
- Load balancers
- Multiple WebSocket servers
- Connection management
- Pub/Sub systems
- Redis or similar messaging systems
- Horizontal scaling
A messaging layer can allow multiple WebSocket servers to share events.
For example:
WebSocket Server A ──┐
↓
Redis
↑
WebSocket Server B ──┘
This can help distribute real-time messages across multiple application instances.
WebSocket vs REST API
WebSockets and REST APIs are not necessarily competitors.
In many applications, they work together.
For example:
REST API
↓
Login
Get Users
Create Order
Get Profile
WebSocket
↓
Live Notifications
Chat
Order Status
Real-Time Updates
A typical application might use REST APIs for standard CRUD operations and WebSockets for real-time events.
When Should You Use WebSocket?
Use WebSockets when your application needs:
- Real-time communication
- Frequent server updates
- Bidirectional communication
- Low-latency messaging
- Live notifications
- Chat
- Multiplayer functionality
- Collaborative features
- Live dashboards
You probably don’t need WebSockets when your application mainly performs:
- Standard CRUD operations
- Occasional API requests
- Static content delivery
- Traditional page rendering
- Infrequent data retrieval
In those cases, HTTP and REST APIs may be simpler.
WebSocket Best Practices
When building a production WebSocket application, consider these practices:
Handle Reconnection
Networks can fail. Your client should be able to reconnect when appropriate.
Validate Messages
Validate every incoming message before processing it.
Use Authentication
Make sure only authorized users can access protected WebSocket channels.
Use Secure WebSockets
Use wss:// in production.
Monitor Connections
Track active connections, connection failures, and message rates.
Keep Messages Small
Avoid sending unnecessarily large messages through a persistent connection.
Plan for Scaling
If your application expects many simultaneous users, design your WebSocket infrastructure for horizontal scaling.
WebSocket and Modern Web Applications
WebSockets remain an important technology for real-time applications.
Modern applications often combine several communication patterns instead of relying on one protocol for everything.
For example:
Frontend
|
├── REST API → CRUD Operations
|
├── WebSocket → Real-Time Events
|
└── CDN → Static Assets
This hybrid approach allows each technology to handle the type of communication it is best suited for.
Conclusion
So, what is WebSocket?
WebSocket is a communication protocol that provides a persistent, bidirectional connection between a client and server.
Unlike traditional request-response communication, WebSockets allow both sides to send data whenever necessary. This makes them especially useful for applications that require real-time communication.
WebSockets are commonly used for:
- Chat applications
- Live notifications
- Multiplayer games
- Real-time dashboards
- Collaborative applications
- Live tracking
- Financial applications
- Real-time monitoring
However, WebSockets are not a replacement for HTTP or REST APIs. In many modern applications, REST APIs and WebSockets work together, with REST handling standard API operations and WebSockets handling real-time events.
Understanding how WebSockets work is an important skill for modern frontend, backend, and full-stack developers.
Frequently Asked Questions
What is WebSocket in simple terms?
WebSocket is a technology that creates a persistent connection between a client and server, allowing both sides to exchange messages in real time.
Is WebSocket better than HTTP?
Not necessarily. HTTP is better for many standard web requests, while WebSocket is better for real-time, bidirectional communication.
Is WebSocket an API?
WebSocket is a communication protocol. Browsers provide a WebSocket API that developers can use to create and manage WebSocket connections.
What is the difference between WebSocket and REST API?
REST APIs typically use a request-response model, while WebSockets maintain a persistent connection that allows both the client and server to send messages independently.
Can WebSocket work with Node.js?
Yes. Node.js is commonly used to build WebSocket servers using libraries such as ws and Socket.IO.
Is WebSocket secure?
WebSockets can be secured using wss://, which encrypts communication using TLS. Applications should also implement appropriate authentication, authorization, and message validation.
Does WebSocket replace REST API?
No. WebSockets and REST APIs solve different problems and can be used together in the same application.
When should I use WebSocket?
Use WebSockets when you need real-time, low-latency, bidirectional communication, such as chat, live notifications, multiplayer games, collaborative tools, or real-time dashboards.




