Okay, let's create a full-stack web application for URL shortening using WebSockets.
Why WebSockets for URL Shortening?
While a simple HTTP request/response cycle is perfectly fine for URL shortening, using WebSockets demonstrates their capabilities for real-time communication. In this specific scenario, the benefits are less about "real-time updates" for multiple users (like a chat app) and more about:
- Illustrative Example: It's a great way to showcase how a client and server can maintain a persistent, bidirectional connection.
- Potential for Future Features: If you wanted to add features like:
- Real-time analytics for a shortened URL (e.g., "5 clicks in the last minute!").
- Push notifications to the user who shortened the URL when someone clicks it.
- A dashboard that updates live with new shortened URLs or click events.
- This is where WebSockets would shine.
Core Components:
- Frontend (HTML, CSS, JavaScript):
- HTML for the input form and result display.
- CSS for basic styling.
- JavaScript to handle user input, establish the WebSocket connection, send the long URL, and display the shortened URL received from the server.
- Backend (Node.js with
ws and express):
express to serve the static frontend files and handle the redirection for shortened URLs.
ws library to create and manage the WebSocket server.
- Logic to generate unique short codes and store the mapping between short code and long URL.
- Handle WebSocket messages (shorten request) and send responses (shortened URL).
Project Setup
-
Create a project directory:
mkdir url-shortener-ws
cd url-shortener-ws
-
Initialize Node.js project:
npm init -y
-
Install dependencies:
npm install express ws
-
Create file structure:
url-shortener-ws/
├── public/
│ ├── index.html
│ ├── style.css
│ └── script.js
└── server.js
1. Backend (server.js)
This file will handle the HTTP server (for serving static files and redirects) and the WebSocket server.
// server.js
const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const path = require('path');
const app = express();
const port = 3000;
// In-memory store for URLs (for demonstration purposes)
// In a real application, you would use a database (e.g., Redis, MongoDB, PostgreSQL)
const urlMap = new Map(); // Maps shortCode -> longUrl
// --- Helper function to generate a short code ---
function generateShortCode() {
let shortCode;
do {
// Generate a random 6-character alphanumeric string
shortCode = Math.random().toString(36).substring(2, 8);
} while (urlMap.has(shortCode)); // Ensure uniqueness
return shortCode;
}
// --- Serve static files from the 'public' directory ---
app.use(express.static(path.join(__dirname, 'public')));
// --- Handle HTTP GET requests for shortened URLs (redirection) ---
app.get('/:shortCode', (req, res) => {
const { shortCode } = req.params;
const longUrl = urlMap.get(shortCode);
if (longUrl) {
console.log(`Redirecting ${shortCode} to ${longUrl}`);
// Ensure the URL has a protocol (http/https) for redirection
if (!longUrl.startsWith('http://') && !longUrl.startsWith('https://')) {
res.redirect(`http://${longUrl}`); // Default to http if not specified
} else {
res.redirect(longUrl);
}
} else {
res.status(404).send('URL not found');
}
});
// --- Create HTTP server ---
const server = http.createServer(app);
// --- Create WebSocket server and attach it to the HTTP server ---
const wss = new WebSocket.Server({ server });
wss.on('connection', ws => {
console.log('Client connected to WebSocket.');
ws.on('message', message => {
try {
const data = JSON.parse(message);
console.log('Received from client:', data);
if (data.type === 'shorten' && data.longUrl) {
const longUrl = data.longUrl;
const shortCode = generateShortCode();
urlMap.set(shortCode, longUrl);
const shortUrl = `http://localhost:${port}/${shortCode}`; // Construct full short URL
// Send the shortened URL back to the client
ws.send(JSON.stringify({
type: 'shortened',
originalUrl: longUrl,
shortUrl: shortUrl
}));
console.log(`URL shortened: ${longUrl} -> ${shortUrl}`);
} else {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid request' }));
}
} catch (error) {
console.error('Error parsing message or processing request:', error);
ws.send(JSON.stringify({ type: 'error', message: 'Server error' }));
}
});
ws.on('close', () => {
console.log('Client disconnected from WebSocket.');
});
ws.on('error', error => {
console.error('WebSocket error:', error);
});
});
// --- Start the server ---
server.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
console.log(`WebSocket server running on ws://localhost:${port}`);
});
2. Frontend Files
a. public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket URL Shortener</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>URL Shortener</h1>
<div class="input-section">
<input type="text" id="longUrlInput" placeholder="Enter long URL here (e.g., https://www.example.com)">
<button id="shortenBtn">Shorten URL</button>
</div>
<div id="resultDiv" class="result-section">
<p id="statusMessage"></p>
<p id="originalUrl"></p>
<p id="shortUrlDisplay"></p>
</div>
<div class="instructions">
<p><strong>How it works:</strong></p>
<ol>
<li>Enter a long URL and click "Shorten URL".</li>
<li>Your browser sends the URL to the server via a WebSocket connection.</li>
<li>The server generates a short code, stores the mapping, and sends the short URL back to your browser via the same WebSocket.</li>
<li>The short URL is displayed, ready for you to copy and share!</li>
</ol>
<p>Refresh the page or restart the server to clear all shortened URLs (they are stored in-memory for this demo).</p>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
b. public/style.css
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: flex-start; /* Align to top for better content flow */
min-height: 100vh;
margin: 20px;
box-sizing: border-box;
}
.container {
background-color: #fff;
padding: 30px;
border-radius: 8px;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
text-align: center;
width: 100%;
max-width: 600px;
}
h1 {
color: #333;
margin-bottom: 30px;
}
.input-section {
display: flex;
margin-bottom: 20px;
flex-wrap: wrap; /* Allow wrapping on smaller screens */
justify-content: center;
}
#longUrlInput {
flex-grow: 1;
padding: 12px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 16px;
margin-right: 10px;
min-width: 200px; /* Ensure input is not too small */
}
#shortenBtn {
padding: 12px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
#shortenBtn:hover {
background-color: #0056b3;
}
.result-section {
background-color: #e9ecef;
padding: 15px;
border-radius: 5px;
text-align: left;
min-height: 80px; /* Give some space even when empty */
display: flex;
flex-direction: column;
justify-content: center;
}
#statusMessage {
color: #666;
font-style: italic;
margin-bottom: 5px;
}
#originalUrl, #shortUrlDisplay {
margin: 5px 0;
word-wrap: break-word; /* Break long URLs */
}
#originalUrl strong {
color: #555;
}
#shortUrlDisplay strong {
color: #007bff;
font-size: 1.1em;
}
#shortUrlDisplay a {
color: #007bff;
text-decoration: none;
font-weight: bold;
}
#shortUrlDisplay a:hover {
text-decoration: underline;
}
.instructions {
margin-top: 30px;
background-color: #f8f9fa;
padding: 20px;
border-radius: 8px;
text-align: left;
border: 1px solid #e0e0e0;
}
.instructions p {
margin-bottom: 10px;
line-height: 1.5;
color: #444;
}
.instructions ol {
margin-left: 20px;
padding-left: 0;
list-style-type: decimal;
color: #444;
}
.instructions li {
margin-bottom: 8px;
}
/* Responsive adjustments */
@media (max-width: 600px) {
.input-section {
flex-direction: column;
}
#longUrlInput {
margin-right: 0;
margin-bottom: 10px;
}
#shortenBtn {
width: 100%;
}
}
c. public/script.js
// script.js
document.addEventListener('DOMContentLoaded', () => {
const longUrlInput = document.getElementById('longUrlInput');
const shortenBtn = document.getElementById('shortenBtn');
const statusMessage = document.getElementById('statusMessage');
const originalUrlDisplay = document.getElementById('originalUrl');
const shortUrlDisplay = document.getElementById('shortUrlDisplay');
// Establish WebSocket connection
// Use 'ws://' for development. For 'https' in production, use 'wss://'
// You might need to adjust the host if your server isn't on the same machine/port
const ws = new WebSocket('ws://localhost:3000');
ws.onopen = () => {
console.log('WebSocket connection established.');
statusMessage.textContent = 'Connected to server.';
statusMessage.style.color = 'green';
};
ws.onmessage = event => {
const data = JSON.parse(event.data);
console.log('Received from server:', data);
if (data.type === 'shortened') {
statusMessage.textContent = 'URL Shortened Successfully!';
statusMessage.style.color = 'green';
originalUrlDisplay.innerHTML = `<strong>Original:</strong> <a href="${data.originalUrl}" target="_blank">${data.originalUrl}</a>`;
shortUrlDisplay.innerHTML = `<strong>Shortened:</strong> <a href="${data.shortUrl}" target="_blank">${data.shortUrl}</a>`;
} else if (data.type === 'error') {
statusMessage.textContent = `Error: ${data.message}`;
statusMessage.style.color = 'red';
originalUrlDisplay.textContent = '';
shortUrlDisplay.textContent = '';
}
};
ws.onclose = () => {
console.log('WebSocket connection closed.');
statusMessage.textContent = 'Disconnected from server. Please refresh.';
statusMessage.style.color = 'red';
};
ws.onerror = error => {
console.error('WebSocket error:', error);
statusMessage.textContent = 'WebSocket error. Check console.';
statusMessage.style.color = 'red';
};
shortenBtn.addEventListener('click', () => {
const longUrl = longUrlInput.value.trim();
if (!longUrl) {
statusMessage.textContent = 'Please enter a URL.';
statusMessage.style.color = 'orange';
originalUrlDisplay.textContent = '';
shortUrlDisplay.textContent = '';
return;
}
if (ws.readyState === WebSocket.OPEN) {
statusMessage.textContent = 'Sending URL to server...';
statusMessage.style.color = 'blue';
// Send the long URL to the server via WebSocket
ws.send(JSON.stringify({ type: 'shorten', longUrl: longUrl }));
longUrlInput.value = ''; // Clear input field
} else {
statusMessage.textContent = 'WebSocket not connected. Please refresh the page.';
statusMessage.style.color = 'red';
}
});
// Optional: Allow shortening by pressing Enter key
longUrlInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
shortenBtn.click();
}
});
});
How to Run
- Open your terminal and navigate to the
url-shortener-ws directory.
- Start the server:
node server.js
You should see output like:
Server running on http://localhost:3000
WebSocket server running on ws://localhost:3000
- Open your web browser and go to
http://localhost:3000.
- Enter a long URL (e.g.,
https://www.google.com or https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) into the input field and click "Shorten URL".
- The shortened URL will appear below. You can click on it to test the redirection.
How it Works
-
Server Initialization (server.js):
- An
Express app is created to handle HTTP requests.
- It serves static files (your
index.html, style.css, script.js) from the public directory.
- A standard
http.Server is created using the Express app.
- A
WebSocket.Server instance is created and attached to the http.Server. This means both HTTP requests and WebSocket connections will run on the same port (3000).
- An in-memory
Map (urlMap) stores the shortCode to longUrl mappings.
-
HTTP Redirection:
- When you navigate to a shortened URL like
http://localhost:3000/abcdef, the app.get('/:shortCode', ...) route catches this request.
- It looks up
abcdef in urlMap. If found, it issues an HTTP 302 Redirect to the original long URL. If not found, it sends a 404.
-
Client-Side WebSocket Connection (script.js):
- When
index.html loads, script.js immediately attempts to establish a WebSocket connection to ws://localhost:3000.
ws.onopen fires when the connection is successful, updating the status message.
-
Shortening a URL (Client-to-Server via WebSocket):
- When you type a URL and click "Shorten URL" on the frontend:
- The JavaScript gets the URL from the input field.
- It sends a JSON message (
{ type: 'shorten', longUrl: '...' }) to the server using ws.send().
-
Server-Side WebSocket Handling (server.js - wss.on('connection')):
- When the server receives a message from a client via WebSocket (
ws.on('message')):
- It parses the JSON message.
- If
data.type is 'shorten' and data.longUrl exists:
- It generates a unique
shortCode.
- It stores the
longUrl in with the as the key.
Limitations and Improvements
- Persistence: The
urlMap is in-memory. All shortened URLs will be lost if the server restarts. For a production application, you would integrate a database (e.g., PostgreSQL, MySQL, MongoDB, Redis) to store the mappings persistently.
- Error Handling: Basic error handling is included, but a production app would need more robust validation (e.g., ensuring
longUrl is a valid URL format) and error responses.
- Security: This demo has no security features. A real application would need:
- Input Sanitization: To prevent XSS attacks.
- Rate Limiting: To prevent abuse.
- HTTPS/WSS: For encrypted communication.
- Authentication/Authorization: If you want users to manage their own shortened URLs.
- Short Code Generation: The
Math.random().toString(36).substring(2, 8) method is simple but not cryptographically strong and collisions become more likely with many URLs. For a large-scale system, you'd use more sophisticated, perhaps base-62 (0-9, a-z, A-Z) encoding with incrementing IDs or a distributed ID generator.
- Scalability: In-memory
urlMap is not scalable for multiple server instances. A shared, external database is necessary for horizontal scaling.
- Domain Name: Currently uses
localhost. For public use, you'd configure a real domain name.
- User Interface: Very basic. Could be improved with copy-to-clipboard functionality, better feedback, etc.