Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 43 ยท Projects

Project: URL Shortener Service

Build a URL shortener: create, redirect and stats endpoints, URL validation, a rate limiter and a lookup cache. Real Express code is read-only; a runnable stand-in is included.

A URL shortener looks tiny, yet it touches many real backend topics: validating untrusted input, generating unique codes, redirects, counting hits, caching hot lookups and protecting the service from abuse. In this project you build one with three endpoints: create a short link, follow it, and read its statistics.

As elsewhere in this course, real Express code is read-only and the runnable parts use our stand-in framework, which has the familiar app.get, app.post, req.params, res.json and next. The business logic (validation, codes, limiter, cache) is plain JavaScript that would run unchanged inside real Express.

Three endpoints

POST /api/links Send a long URL, get a short code.
GET /:code Redirect with 302 and count the hit.
GET /api/links/:code/stats Show how often it was used.
1 / 2

Design decisions

Which redirect status? 301 means "moved permanently" and browsers cache it, which hides later clicks from your counter and makes it hard to change a target. 302 (or 307) is not cached, so every click reaches your server. A shortener that counts hits wants 302.

How to make codes? Random strings need a collision check. A simpler method is to give each link an auto-incrementing number and write it in base 62 (0-9a-zA-Z): 1 becomes 1, 62 becomes 10. The codes are short and guaranteed unique. Their drawback is that they are guessable and reveal how many links exist; if that matters, shuffle the alphabet or use random codes with a unique database index.

What may be shortened? A shortener that accepts javascript: or data: URLs becomes a phishing and XSS tool. Parse with new URL() and allow only http: and https:. Reject very long inputs, and consider refusing URLs that point at your own domain, so a link cannot redirect to itself in a loop.

JavaScript
function parseTarget(input) {
  if (typeof input !== 'string' || input.length > 2048) return null;
  try {
    const url = new URL(input);
    return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null;
  } catch {
    return null;
  }
}

const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function toBase62(number) {
  let code = '';
  do {
    code = ALPHABET[number % 62] + code;
    number = Math.floor(number / 62);
  } while (number > 0);
  return code;
}

The real Express version (read-only)

Here is the service in real Express 5, with the rate limiter from the express-rate-limit package:

JavaScript
import express from 'express';
import rateLimit from 'express-rate-limit';

const app = express();
app.set('trust proxy', 1);          // behind a proxy, so req.ip is the real client
app.use(express.json({ limit: '4kb' }));

const links = new Map();            // code -> { url, hits, createdAt }
let counter = 0;

const createLimiter = rateLimit({
  windowMs: 60_000,
  limit: 5,
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'Too many links created, slow down' },
});

app.post('/api/links', createLimiter, (req, res) => {
  const url = parseTarget(req.body?.url);
  if (!url) return res.status(422).json({ error: 'A valid http or https URL is required' });
  const code = toBase62(++counter);
  links.set(code, { url, hits: 0, createdAt: new Date().toISOString() });
  res.status(201).json({ code, short: `${req.protocol}://${req.get('host')}/${code}` });
});

app.get('/api/links/:code/stats', (req, res) => {
  const link = links.get(req.params.code);
  if (!link) return res.status(404).json({ error: 'Unknown code' });
  res.json({ code: req.params.code, ...link });
});

// Registered LAST so it does not shadow other single-segment routes.
app.get('/:code', (req, res) => {
  const link = links.get(req.params.code);
  if (!link) return res.status(404).send('Unknown short link');
  link.hits++;
  res.redirect(302, link.url);
});

Route order matters twice here. GET /:code matches any one-segment path, so it must be registered after fixed routes like /health or /favicon.ico, which would otherwise be treated as codes (Routing Basics). And the limiter is attached only to the create route; redirects must stay fast and unrestricted.

Runnable stand-in: create, redirect, stats

This example runs the three endpoints. The fetch calls use redirect: 'manual', so you can see the 302 and its Location header instead of the browser following them.

Node.js Create, follow and measure links

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first created code is 10 because the demo starts counting at 62 (base 62 for 62 is 10), which shows how codes grow. javascript: URLs and plain text are rejected with 422. After two visits, the stats show hits: 2.

Rate limiting and caching

Two production features turn the toy into a service.

A rate limiter counts requests per client in a time window and answers 429 Too Many Requests when the budget is spent. The simplest design is a fixed window: a Map from client key to { count, resetAt }. It is cheap, and good enough to stop casual abuse, though a client can burst at a window boundary. The key is normally req.ip; that is why trust proxy matters behind a load balancer. With several server processes, the counters must live in a shared store like Redis, otherwise each process allows its own full budget (Security Best Practices).

A cache keeps the answer for a hot code in memory so the database is not queried on every click. Short links are an ideal case: they are read thousands of times for each write, and the target rarely changes. Keep entries for a limited time (TTL), and delete or update the entry when a link changes. Counters make caching a little subtle: update hits in memory and write them to the database in batches.

Both features take the clock as a parameter below, so the example needs no waiting.

Node.js A fixed-window rate limiter and a TTL cache

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Alice gets three successful creations, then 429 with a retry-after value, while Bob has his own budget. After the window resets she can create again. For the cache, only the first and the post-expiry lookups touch the database: two reads for three requests.

Hardening checklist

  • Abuse: shorteners are popular with spammers. Add per-client limits, block known bad domains and offer a report link.
  • Open redirect risk: never redirect to a URL taken from a query parameter without validating it; here targets are stored at creation time and validated then.
  • Collisions: custom aliases need a uniqueness check and a reserved list (api, admin, health).
  • Analytics: log hits to a queue or table instead of updating a counter row on every click.
  • Expiry and deletion: support an expiresAt and return 410 Gone for removed links.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a click-counting shortener prefer a 302 redirect over a 301?

    A permanent redirect may be cached by the browser, hiding repeat visits from your counter and making target changes hard.
  2. 2. Why must the GET /:code route be registered after fixed routes like /health?

    Routes are tried in order, and /:code matches /health too, so it has to come last.
  3. 3. What does a fixed-window rate limiter track for each client?

    Counting within a window and resetting when it ends is the whole algorithm, and it is cheap to store.
  4. 4. Which URL must the service refuse to shorten?

    Only http and https targets are safe. javascript: and data: URLs turn the service into an attack tool.

Summary

  • Use 302 for redirects you want to count; 301 is cached by browsers.
  • Generate codes from a counter in base 62, or random codes with a unique index.
  • Parse with new URL() and allow only http and https.
  • Put a rate limiter on creation, keyed by client IP, and 429 with Retry-After when exceeded.
  • Cache hot lookups with a TTL; update or delete entries when links change.
  • Register catch-all style routes like /:code last.

Next: Project: File Upload and Download Service.