Introduction
Real-time communication is essential for modern web applications, powering features like live chat, notifications, collaborative tools, and stock market dashboards. WebSockets provide a persistent, full-duplex connection between the client and server, making real-time interactions seamless.
This guide covers how to implement WebSockets in a web app using Node.js, Next.js, and Firebase.
Why Use WebSockets?
✔ Real-Time Updates – Instant data exchange without polling.
✔ Reduced Latency – Faster communication compared to HTTP requests.
✔ Bidirectional Communication – Both client and server can send messages.
✔ Efficient Resource Usage – No need for frequent API requests.
Setting Up WebSockets in Node.js
- Install Dependencies
First, install WebSocket support in a Node.js app:
npm install ws express
- Create a WebSocket Server
Create server.js and set up a basic WebSocket server:
const WebSocket = require('ws');
const express = require('express');
const app = express();
const server = require('http').createServer(app);
const wss = new WebSocket.Server({ server });
wss.on('connection', (ws) => {
console.log('New client connected');
ws.on('message', (message) => {
console.log(`Received: ${message}`);
ws.send(`Server response: ${message}`);
});
ws.on('close', () => console.log('Client disconnected'));
});
server.listen(3000, () => console.log('Server running on port 3000'));
- Connect the Client
On the frontend, connect to the WebSocket server:
const socket = new WebSocket('ws://localhost:3000');
socket.onopen = () => console.log('Connected to WebSocket server');
socket.onmessage = (event) => console.log('Received:', event.data);
socket.onclose = () => console.log('Disconnected');
Using WebSockets with Next.js
- Set Up a WebSocket API Route
Inside pages/api, create websocket.ts:
import { NextApiRequest, NextApiResponse } from 'next';
import { Server } from 'ws';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (!res.socket.server.ws) {
const wss = new Server({ noServer: true });
res.socket.server.on('upgrade', (request, socket, head) => {
wss.handleUpgrade(request, socket, head, (ws) => {
ws.on('message', (message) => {
console.log(`Received: ${message}`);
ws.send(`Server response: ${message}`);
});
});
});
res.socket.server.ws = wss;
}
res.end();
}
- Connect the Frontend to WebSockets
Modify pages/index.tsx to listen for real-time updates:
import { useEffect, useState } from 'react';
export default function Home() {
const [messages, setMessages] = useState<string[]>([]);
useEffect(() => {
const socket = new WebSocket('ws://localhost:3000/api/websocket');
socket.onmessage = (event) => {
setMessages((prev) => [...prev, event.data]);
};
return () => socket.close();
}, []);
return (
<div>
<h1>WebSocket Messages</h1>
<ul>{messages.map((msg, i) => <li key={i}>{msg}</li>)}</ul>
</div>
);
}
Using Firebase WebSockets with Firestore
- Install Firebase
npm install firebase
- Set Up Firestore Listeners
import { getFirestore, collection, onSnapshot } from 'firebase/firestore';
const db = getFirestore();
onSnapshot(collection(db, 'messages'), (snapshot) => {
snapshot.docs.forEach((doc) => console.log(doc.data()));
});
Conclusion
WebSockets enable real-time communication for applications like chat apps, live notifications, stock tickers, and collaborative tools. This guide covered:
✔ Setting up WebSockets in Node.js
✔ Implementing WebSockets in Next.js API routes
✔ Using Firebase Firestore for real-time data synchronization
I am open to collaboration on projects and work. Let's transform ideas into digital reality.
Top comments (0)