Last Updated : 23 Jul, 2025
In today's high-speed, digitally driven world, users want instant updates and interactions from the web applications they visit. This real-time functionality allows for instant data exchange and interaction, which is a very important component for creating engaging user experiences. This article explores how to effectively implement such real-time features into your web app, covering technologies, strategies, and best practices.
Understanding Real-Time FeaturesReal-time applications avoid latency by communicating instantly between clients and servers for better interactivity . Some examples of this are online gaming platforms , live chat services , webinar services , and financial application s that integrate real-time stock updates . Real-time apps reject the latency brought about by traditional HTTP requests using multiple connections to permanent ones in order to push data instantly to the clients for a more dynamic and engaging user experience.
Why Real-Time Features MatterTechnologies for Building Real-Time Web Applications 1. WebSocketIf you're interested in learning more about how to develop such features, mastering the MERN Full Stack is an essential skill. The GeeksforGeeks MERN Full Stack Development Course offers hands-on learning for building dynamic, real-time web applications. This course covers critical technologies such as React.js, Node.js, and WebSocket, which are essential for crafting modern web applications with real-time features like those discussed in this article.
A protocol that provides a full-duplex, real-time connection between client and server, enabling simultaneous data transmission in both directions.
Implementation:
An open-source project enabling direct real-time communication between browsers without plugins. Ideal for video calls, voice calls, and peer-to-peer file sharing.
Implementation:
RTCPeerConnection
instances for media and data transmission. APIs that push updates from the server to the client in real time, including GraphQL subscriptions, WebHooks , and Server-Sent Events (SSE).
Implementation :
Ever wonder how your favorite delivery apps, like Zomato, are able to provide live updates on your food's journey from the restaurant to your doorstep? The magic behind these real-time tracking system s is not as complex as it might seem, and you can integrate similar features into your own app with the right approach. One of the key technologies that makes this possible is WebSocket .
What is WebSocket?WebSocket is a communication protocol that enables a full-duplex, persistent connection between a client (your app) and a server. Unlike traditional HTTP communication, which follows a request-response model and involves latency due to repeated connections, WebSocket keeps the connection open, allowing for real-time, bidirectional data exchange.
1. Express and WebSocket Server (Backend of our feature)Note : You should have good knowledge of the Nodejs , express.js, reactjs and web socket then only you can understand this so, it is kind request to have good knowledge of these tech stack before moving to code.
For backend we will use express and WebSocket to make a two way communication between client and server and in this code we have start our local server on 4000 port and created a communication channel using webSocket and we are sending the restaurant location in starting to the client and after that when our order is on the way we are fetching the delivery partner's location and sending it to client after every 5 sec (You can change this according to you need but this is industry standard).
JavaScriptNote: The Delivery's partner location is fetched from the another part of the code that we cant show or explain here but to replicate this we are using Math.random library to change the location but in real it will be fetched from another part of the code.
const express = require("express");
const WebSocket = require("ws");
const app = express();
const port = 4000;
// Serve static files from the React app
app.use(express.static("public"));
// Start the Express server
const server = app.listen(port, () => {
console.log(
`Server is running on http://localhost:${port}`);
});
// Initialize WebSocket server
const wss = new WebSocket.Server({server});
// Function to broadcast data to all connected clients
const broadcast = (data) => {
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
};
// Handle WebSocket connections
wss.on("connection", (ws) => {
console.log("New client connected");
// Simulate delivery partner GPS location updates and
// order status
setInterval(() => {
const location = {
type : "location",
data : {
latitude :
37.7749
+ Math.random()
* 0.01, // Simulate latitude
// changes
longitude :
-122.4194
+ Math.random()
* 0.01, // Simulate longitude
// changes
},
};
const orderStatus = {
type : "orderStatus",
data : {
status : "On the way", // Example status
},
};
broadcast(location);
broadcast(orderStatus);
}, 5000); // Send location updates every 5 seconds
ws.on("close",
() => { console.log("Client disconnected"); });
});
Detailed Flow
Initialize the Application
Serve Static Files
public
. These files could be the HTML, CSS, and JavaScript files necessary to run a front-end application. Start the Express Server
Initialize WebSocket Server
Handle WebSocket Connections
Simulate Data Updates
Broadcast Function
Handle Client Disconnection
The frontend of the delivery tracking application is built using React and leverages several libraries and technologies to provide an interactive and real-time user experience. Here's a detailed breakdown of the frontend components:
Main Technologies Used:
import React, { useEffect, useState } from 'react';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet-routing-machine/dist/leaflet-routing-machine.css';
import 'leaflet-routing-machine';
function DeliveryMap({ userLocation, restaurantLocation, tracking }) {
const [map, setMap] = useState(null); // State to store the map instance
const [routingControl, setRoutingControl] = useState(null); // State to store the routing control instance
const [deliveryMarker, setDeliveryMarker] = useState(null); // State to store the delivery marker instance
useEffect(() => {
// Initialize the map with the user's location
const initMap = L.map('map').setView([userLocation.latitude, userLocation.longitude], 13);
// Add OpenStreetMap tiles to the map
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(initMap);
// Add markers for user and restaurant locations
const userMarker = L.marker([userLocation.latitude, userLocation.longitude]).addTo(initMap).bindPopup('Your Location').openPopup();
const restaurantMarker = L.marker([restaurantLocation.latitude, restaurantLocation.longitude]).addTo(initMap).bindPopup('Restaurant Location').openPopup();
// Store the map instance in state
setMap(initMap);
return () => {
// Cleanup the map instance on unmount
initMap.remove();
};
}, [userLocation, restaurantLocation]);
useEffect(() => {
if (map && tracking) {
// Add a marker for the delivery location
const deliveryMarker = L.marker([userLocation.latitude, userLocation.longitude]).addTo(map).bindPopup('Delivery Location').openPopup();
setDeliveryMarker(deliveryMarker);
// Initialize routing control with waypoints from restaurant to delivery location
const routingControl = L.Routing.control({
waypoints: [
L.latLng(restaurantLocation.latitude, restaurantLocation.longitude),
L.latLng(userLocation.latitude, userLocation.longitude)
],
routeWhileDragging: true,
showAlternatives: true,
altLineOptions: {
styles: [{ color: 'black', opacity: 0.15, weight: 9 }]
},
createMarker: function() { return null; }
}).addTo(map);
// Store the routing control instance in state
setRoutingControl(routingControl);
// Open a WebSocket connection to receive real-time updates
const socket = new WebSocket('ws://localhost:4000');
// Handle messages from the WebSocket
socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.type === 'location') {
// Update the delivery marker and route waypoints with new location data
deliveryMarker.setLatLng([message.data.latitude, message.data.longitude]);
routingControl.setWaypoints([
L.latLng(restaurantLocation.latitude, restaurantLocation.longitude),
L.latLng(message.data.latitude, message.data.longitude)
]);
}
});
return () => {
// Cleanup WebSocket, delivery marker, and routing control on unmount
socket.close();
map.removeLayer(deliveryMarker);
map.removeControl(routingControl);
};
}
}, [map, tracking, restaurantLocation, userLocation]);
return <div id="map" style={{ height: '400px', width: '100%' }}></div>;
}
export default DeliveryMap;
Detail Flow
Component Initialization
DeliveryMap
is initialized with properties for the user's location ( userLocation
), the restaurant's location ( restaurantLocation
), and a flag to enable tracking ( tracking
). State Management
map
to store the Leaflet map instance. routingControl
to store the instance that manages the routing on the map.
deliveryMarker
to store the marker representing the delivery's current location. Map Setup
Handling Tracking
WebSocket Connection
Cleanup
import React, { useState } from 'react';
import DeliveryMap from './components/DeliveryMap';
function App() {
const [tracking, setTracking] = useState(false); // State to manage whether tracking is enabled
const userLocation = { latitude: 37.7749, longitude: -122.4194 }; // Example coordinates for user location
const restaurantLocation = { latitude: 37.7849, longitude: -122.4094 }; // Example coordinates for restaurant location
// Function to start tracking
const startTracking = () => {
setTracking(true);
};
return (
<div>
<h1>Delivery App</h1>
<DeliveryMap
userLocation={userLocation}
restaurantLocation={restaurantLocation}
tracking={tracking}
/>
{!tracking && <button onClick={startTracking}>Start Tracking</button>}
</div>
);
}
export default App;
Detail Flow
Component Initialization
App
is initialized. This component manages the overall state and user interface. State Management
useState
hook to manage the tracking state: tracking
is a boolean state that indicates whether delivery tracking is enabled. setTracking
is a function to update the tracking
state. Define Locations
userLocation
represents the user's coordinates. restaurantLocation
represents the restaurant's coordinates. Start Tracking Function
startTracking
is defined to enable tracking: tracking
state to true
. Render Method
App
component's render method includes:
DeliveryMap
component, which is passed the user's location, the restaurant's location, and the current tracking state as props. startTracking
function to enable tracking. This button is only displayed if tracking is not already enabled. Read MoreConclusion
We hope this article has clearly explained the essence of real-time features in web applications, particularly in delivery tracking systems similar to Zomato's. Using WebSocket, you can enable live updates with bi-directional communication between your app and server, keeping users updated in real-time with accurate information.
Real-time features improve the user experience by providing timely updates and seamless interactions. With WebSocket, the location keeps updating while the consumer is on track, ensuring customers are kept informed about their order in real-time.
Mastering these principles and applying the appropriate technologies can help you implement real-time capabilities in your apps, ensuring increased engagement and better functionality delivery.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4