URL Shortener Project in Node.js — a practical guide to Node.js URL shortener with clear examples you can reuse in real projects.
URL Shortener Project in Node.js — 33/55 in the Node.js series. Full playlist companion: Node.js complete course on YouTube. Prefer one article? Read the complete Node.js tutorial.
Short description
Store mappings in memory/JSON/DB, generate short IDs, and redirect with HTTP 302 when a short code is visited.
In-memory shortener sketch
const http = require('http');
const map = new Map();
http.createServer((req, res) => {
if (req.method === 'POST' && req.url === '/shorten') {
let body = '';
req.on('data', (c) => (body += c));
req.on('end', () => {
const { url } = JSON.parse(body);
const code = Math.random().toString(36).slice(2, 8);
map.set(code, url);
res.end(JSON.stringify({ short: code }));
});
return;
}
const code = req.url.slice(1);
if (map.has(code)) {
res.writeHead(302, { Location: map.get(code) });
return res.end();
}
res.writeHead(404);
res.end('Not found');
}).listen(3000);