Build a Minimal URL Shortener in Node.js and Redis
Hands-on tutorial: build a working URL shortener with Node.js, Express and Redis. Random Base62 codes, atomic inserts, redirects, expiry and click counts.
Published November 27, 2026
After all the design discussion, it helps to see how small the core really is. In this tutorial you will build a working URL shortener in about 80 lines of Node.js using Express and Redis: create links with random Base62 codes, prevent collisions atomically, redirect with a 302, support expiry, and count clicks. It is a solid starting point you can grow into the scaled design.
The concept
Redis is a good fit for a first version because the data is a simple key-value mapping and Redis gives you atomic primitives for free. SET with the NX option writes a key only if it does not exist, which is exactly the uniqueness check a shortener needs. Optional expiry is just a TTL on the key. Click counts use INCR, which is atomic and very fast.
For production you would add a durable database behind Redis (or enable Redis persistence with AOF), authentication, URL validation and threat checks, but the request flow you build here (validate, generate, insert-if-absent, redirect, count) stays the same.
What we are building
Plan
- npm init and install express, redis, dotenv
- Write a secure random Base62 code generator
- POST /api/links: validate, SET NX with optional EX, retry on collision
- GET /:code: GET the URL, increment click counter, 302 redirect
- GET /api/links/:code/stats: return click count and TTL
The complete server
Save this as server.js. It needs Node 18+ and a local Redis (docker run -p 6379:6379 redis:7).
import express from 'express'
import { createClient } from 'redis'
import { randomInt } from 'node:crypto'
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
const BASE = process.env.BASE_URL ?? 'http://localhost:3000'
const redis = createClient({ url: process.env.REDIS_URL })
await redis.connect()
const app = express()
app.use(express.json({ limit: '10kb' }))
const code = (n = 7) => Array.from({ length: n }, () => ALPHABET[randomInt(62)]).join('')
function validUrl(s) {
try {
const u = new URL(s)
return ['http:', 'https:'].includes(u.protocol) && s.length <= 2048
} catch { return false }
}
app.post('/api/links', async (req, res) => {
const { url, ttlSeconds } = req.body ?? {}
if (!validUrl(url)) return res.status(400).json({ error: 'valid http(s) url required' })
for (let i = 0; i < 5; i++) {
const c = code()
const opts = { NX: true, ...(ttlSeconds ? { EX: Number(ttlSeconds) } : {}) }
if (await redis.set(`link:${c}`, url, opts)) {
return res.status(201).json({ code: c, short_url: `${BASE}/${c}` })
}
}
res.status(503).json({ error: 'could not allocate code, try again' })
})
app.get('/api/links/:code/stats', async (req, res) => {
const [url, clicks, ttl] = await Promise.all([
redis.get(`link:${req.params.code}`),
redis.get(`clicks:${req.params.code}`),
redis.ttl(`link:${req.params.code}`),
])
if (!url) return res.status(404).json({ error: 'not found' })
res.json({ url, clicks: Number(clicks ?? 0), expires_in: ttl > 0 ? ttl : null })
})
app.get('/:code([0-9a-zA-Z]{4,16})', async (req, res) => {
const url = await redis.get(`link:${req.params.code}`)
if (!url) return res.status(404).send('Link not found')
res.set('Cache-Control', 'private, no-store').redirect(302, url)
redis.incr(`clicks:${req.params.code}`).catch(() => {}) // fire and forget
})
app.listen(3000, () => console.log(`listening on ${BASE}`))Trying it out
Practical examples
package.json essentials
ES modules enable top-level await in server.js.
{
"type": "module",
"scripts": { "start": "node server.js" },
"dependencies": { "express": "^4.21.0", "redis": "^4.7.0" }
}Run Redis with persistence
Append-only file persistence keeps links across restarts.
docker run -d --name shortener-redis -p 6379:6379 -v redisdata:/data \
redis:7 redis-server --appendonly yesNext steps toward production
Where to take it from here.
- Durable store (PostgreSQL/DynamoDB) as source of truth; Redis as cache
- Auth + per-key rate limits on POST /api/links
- Safe Browsing check and domain blocklist
- Custom aliases via SET NX on the alias itself
- Click events to a queue instead of INCR for richer analyticsCommon mistakes
- Using Math.random() for codes; use crypto.randomInt so codes are unpredictable.
- Checking existence with GET and then calling SET separately, creating a race; SET NX is atomic.
- Awaiting the click counter before responding, adding latency to every redirect.
- Letting the /:code route swallow /api or /favicon.ico; constrain it with a pattern.
- Running Redis without persistence and losing every link on restart.
Key takeaways
- A working shortener is mostly validation, an atomic insert and a redirect.
- Redis SET NX EX gives uniqueness and expiry in one atomic call.
- Respond first, count clicks asynchronously.
- Add a durable database, auth and abuse checks before going public.
FAQ
Why 302 and not 301?
So every click reaches the server to be counted and links can expire or be disabled. See the redirect article in this series for the trade-off.
How many links can Redis hold?
Each link is roughly 100-200 bytes in Redis, so millions of links fit in a few hundred megabytes of RAM.
Can I deploy this serverless?
Yes, with a managed Redis such as Upstash or ElastiCache Serverless. Keep the redirect function close to users for low latency.