create a website which will use web socket for url shortening
- User
create a website which will use web socket for url shortening
Assistant
Creating a website that uses WebSockets for URL shortening is an interesting approach. While traditional URL shorteners use HTTP POST/GET requests, using WebSockets allows for real-time bidirectional communication between client and server.
Below is a simple example of how you can create a basic URL shortener using:
- Node.js + Express
- WebSocket (via
wslibrary) - Frontend HTML/CSS/JS
🧱 Project Structure
url-shortener-ws/ ├── server.js ├── public/ │ ├── index.html │ └── script.js └── package.json
1️⃣ Initialize the Project
mkdir url-shortener-ws cd url-shortener-ws npm init -y npm install express ws
2️⃣ Server (
server.js)const express = require('express'); const http = require('http'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ server }); // In-memory store for shortened URLs const urlDatabase = {}; let idCounter = 1; // Generate a short ID function generateShortId() { return (idCounter++).toString(36); } // Handle WebSocket connections wss.on('connection', (ws) => { console.log('Client connected.'); ws.on('message', (message) => { const data = JSON.parse(message); if (data.type === 'shorten') { const shortId = generateShortId(); urlDatabase[shortId] = data.url; const shortUrl = `http://localhost:3000/${shortId}`; ws.send(JSON.stringify({ type: 'shortened', shortUrl })); } if (data.type === 'redirect') { const originalUrl = urlDatabase[data.id]; if (originalUrl) { ws.send(JSON.stringify({ type: 'redirect', url: originalUrl })); } else { ws.send(JSON.stringify({ type: 'error', message: 'URL not found' })); } } }); }); // Serve static files app.use(express.static('public')); // Redirect short URLs app.get('/:id', (req, res) => { const originalUrl = urlDatabase[req.params.id]; if (originalUrl) { return res.redirect(originalUrl); } else { return res.status(404).send('URL not found'); } }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server running on http://localhost:${PORT}`); });
3️⃣ Frontend (
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> <style> body { font-family: Arial; padding: 20px; background: #f5f5f5; } input, button { padding: 10px; font-size: 16px; width: 100%; margin-top: 10px; } #result { margin-top: 20px; font-weight: bold; color: green; } </style> </head> <body> <h1>WebSocket URL Shortener</h1> <input type="text" id="urlInput" placeholder="Enter a long URL..." /> <button onclick="shortenUrl()">Shorten</button> <div id="result"></div> <script src="script.js"></script> </body> </html>
4️⃣ Client Script (
public/script.js)const ws = new WebSocket('ws://localhost:3000'); ws.onopen = () => { console.log('Connected to WebSocket server'); }; ws.onmessage = function(event) { const data = JSON.parse(event.data); const resultDiv = document.getElementById("result"); if (data.type === 'shortened') { resultDiv.innerHTML = `Shortened URL: <a href="${data.shortUrl}" target="_blank">${data.shortUrl}</a>`; } else if (data.type === 'redirect') { window.location.href = data.url; } else if (data.type === 'error') { resultDiv.innerHTML = `<span style="color:red;">${data.message}</span>`; } }; function shortenUrl() { const url = document.getElementById("urlInput").value; if (!url) return alert("Please enter a URL"); ws.send(JSON.stringify({ type: 'shorten', url })); }
✅ How It Works
- The user enters a URL in the input box.
- The browser sends a WebSocket message to the server with the URL.
- The server generates a short ID and responds with the shortened link.
- When someone visits the short link (e.g.,
/abc123), they're redirected to the original URL.
🔐 Optional Improvements
- Use Redis or MongoDB instead of in-memory storage.
- Add HTTPS support.
- Add rate limiting.
- Add custom short codes.
- Add analytics for clicks.
▶️ Run the App
node server.jsThen open your browser at:
http://localhost:3000
Let me know if you want this deployed on Heroku, Vercel, or as a Docker container!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.