Skip to content
Tutorials Center
My learning

Topics

Lesson 115 of 133 ยท Projects

Project: URL Shortener

Build a URL shortener in Node.js with the built-in http server and node:sqlite - base62 ids, URL validation, redirects, click counts, error handling and tests against a loopback server.

A URL shortener turns https://example.com/products/2026/spring-collection?ref=newsletter into something like https://sho.rt/1001 and sends visitors to the long address when they open the short one. It looks tiny, yet building one touches a surprising amount of real back-end work: an HTTP server, a database, input validation, redirects, encoding ids, abuse prevention, and tests that talk to a real server.

In this project you will build it with nothing but Node.js itself: the http module and the built-in node:sqlite. We go in stages, and each stage is a complete runnable program. If any of the building blocks feels shaky, revisit The http Module: Servers, SQLite with node:sqlite, URLs and Request Bodies, JSON and Forms.

node:sqlite is built into Node 24 but is still marked experimental, so it prints a one-line warning on standard error. The API we use (DatabaseSync, prepare, run, get, all) has been stable in practice, but check the release notes when you upgrade.

The design in one minute

Three endpoints are enough:

Method and path What it does
POST /api/links with { "url": "..." } Creates a short code (or returns the existing one)
GET /:code Redirects to the original URL and counts the visit
GET /api/links/:code Shows the target URL and the number of visits

The database holds one table: links(id, url, hits). The short code is not stored at all: it is the row id written in base 62. That means no collisions, no retry loops and no second index; decoding the code gives you the primary key to look up.

Stage 1: base62 codes

Base 62 uses the digits 0-9 and the letters A-Z and a-z, so it is compact and URL-safe. Four characters cover 14.7 million links, six cover 56 billion. Encoding is the same repeated division you use to convert to binary, just by 62.

If ids started at 1, the first codes would be 1, 2, 3, which looks silly and reveals how many links you have. We add an offset of 62 cubed (238,328) so that every code has at least four characters.

Node.js Encoding and decoding base62 ids

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 round trip is lossless. Remember that sequential codes are guessable: anyone can walk 1001, 1002, 1003... and discover every link. For public shorteners that is usually fine (the URLs are meant to be shared). If links are private, use random codes instead (see Random Values and IDs), store them in a unique column and retry on a collision, or apply a reversible shuffle to the number before encoding.

Stage 2: validating URLs

The input is a string from an untrusted client, and your shortener will happily send the world's browsers to whatever it stores. Validation is therefore a security feature, not a nicety. The rules:

  1. It must be a string of reasonable length (2,048 characters is generous).
  2. It must parse with new URL(). Relative strings throw, which is what we want.
  3. The protocol must be http: or https:. Reject javascript:, data:, file: and friends.
  4. No embedded credentials (https://user:pass@host), which are used in phishing.
  5. Store the normalized form (url.href), so https://EXAMPLE.com and https://example.com/ count as the same link.
Node.js A validateUrl function with clear errors

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.

Look at the second sample: new URL lowercased the scheme and host and resolved /a/../b to /b. Also notice that example.com with no scheme is rejected: do not try to "fix" it by guessing; a clear error is better. Returning a result object ({ ok, ... }) instead of throwing keeps the common bad-input case cheap and makes the HTTP layer easy to write.

Stage 3: the database

With node:sqlite the whole data layer is a few lines. The UNIQUE constraint on url makes the database itself guarantee that one URL has one code, even if two requests race. We use prepared statements, which are faster when reused and, more importantly, immune to SQL injection because values never get pasted into the SQL text.

Node.js The links table and its queries

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.

hits = hits + 1 is done inside SQL, so it is atomic: two simultaneous visits are both counted. Reading the value into JavaScript, adding one and writing it back would lose updates under concurrency. Last detail: the first two codes are 1001 and 1002, as designed.

Stage 4: the HTTP server

Now we wire everything into an HTTP server. The structure is a function createApp(db) that returns a configured http.Server without starting it. That lets the real program call listen() and tests listen on a random port. Inside is a small router, since there are only three routes.

Pay attention to the details a real service needs:

  • Body limit. Collect the request body while counting bytes, and answer 413 when it passes 10 KB. Never trust an unlimited body.
  • Status codes. 201 Created for a new link, 200 OK when it already existed, 400 for bad input, 404 for unknown codes, 405 for a wrong method, 302 Found for the redirect.
  • A catch-all error handler, so a bug becomes a 500 response and not a crashed process.
  • Location header. Redirects send the stored, already-validated URL.

The demo then plays the client with fetch. We pass redirect: 'manual' so we can see the 302 instead of following it.

Node.js The complete URL shortener server and a client session

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.

Walk through the transcript. The first POST creates code 1001 (201). The identical second POST returns the same code with status 200. javascript: and a non-object body both get 400. Two visits produce two 302 responses with the Location header, and the stats endpoint then reports hits: 2. Unknown or malformed codes give 404 and a wrong method gives 405.

Notice body?.url. When the JSON body is null or a string, body.url would throw a TypeError and turn a client mistake into a 500. Parsing is not validating: always check the shape of what you parsed.

Two design choices deserve thought. First, 302 versus 301. A 301 Moved Permanently is cached by browsers, so later visits skip your server entirely, which saves load but means you lose click counts and cannot change the target. A 302 (or 307) is not cached by default, so every click reaches you. Analytics-driven shorteners use 302. Second, abuse: shorteners are favorite tools of spammers. Real services check targets against block lists, rate-limit creation per client (Scalability and Reliability Patterns shows a token bucket), and refuse to shorten their own domain to avoid redirect loops.

Stage 5: tests against a loopback server

Because createApp returns a server that has not been started, a test can start it on port 0, use fetch against it, and shut it down. This tests the real HTTP behavior (status codes, headers, JSON) with no mocks. See Testing HTTP Servers and CLIs for more patterns.

The next program writes a compact version of the app and its test file into a temporary folder and runs the tests, printing one line per test (the default reporter prints timings that change on every run). Your own project would have app.mjs and app.test.mjs, and you would run node --test.

Node.js Testing the shortener through real HTTP requests

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.

Every test gets a fresh in-memory database and its own server, so tests cannot affect each other and the order does not matter. t.after closes the server even if an assertion throws, which is what lets the process exit. Notice that the tests describe behavior (status codes, headers) rather than internal functions, which is why you could rewrite the storage layer without touching them.

Where to go next

  • Custom aliases: let users pick /summer-sale; check uniqueness and reserve words like api.
  • Expiry and deletion: add expires_at and a cleanup job.
  • Click analytics: store each visit in its own table (time, referrer, country) instead of one counter; write them in batches, as in Processing Large Data Efficiently.
  • Caching: put a small in-memory cache in front of the lookup, because redirects are read far more than they are written.
  • Production hardening: rate limits, Cache-Control, logging, health checks and graceful shutdown (Graceful Shutdown and Health Checks).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the short code derived from the row id instead of being stored separately?

    Encoding the primary key in base 62 gives unique codes for free, and decoding the code gives the key to look up directly.
  2. 2. Why does validateUrl reject javascript:, data: and file: URLs?

    A shortener sends visitors wherever it stored. Limiting the protocol to http and https closes a whole class of abuse.
  3. 3. Why is UPDATE links SET hits = hits + 1 better than reading hits in JavaScript and writing back hits + 1?

    A read-modify-write in JavaScript can interleave with another request and overwrite its update. The database performs the increment as one operation.
  4. 4. What is the trade-off between 301 and 302 redirects for a shortener?

    Permanent redirects can be cached, so repeat visitors skip your server. A shortener that counts clicks or may change targets uses a temporary redirect.
  5. 5. Why does createApp return an unstarted server?

    Separating construction from listening lets the real program choose a port and each test use its own random loopback port.

Summary

  • Encode the integer primary key in base 62 (with an offset for longer codes) instead of storing codes; decode to look the row up.
  • Treat the input URL as hostile: require a string, parse with new URL, allow only http:/https:, forbid credentials, and store the normalized href.
  • Use node:sqlite prepared statements, a UNIQUE constraint to deduplicate, and increment counters in SQL.
  • Build the server as createApp() with a router, a body size limit, correct status codes and a catch-all error handler.
  • Use 302 when you need every click, and think about abuse: rate limits, block lists and self-links.
  • Test through real HTTP on a random loopback port, with a fresh database per test.

Next: Project: A REST API from Scratch