Lesson 19 of 1910:02 video

Build a JavaScript app

The last episode of Learn JavaScript. Build a typing test from an empty folder, with a page, browser storage and a Node server: letters that turn red and green as you type, a timed round, a tested score, a personal best that survives a reload, and a leaderboard every browser shares. Then stop the server in the middle of a round and see what still works.

In this lesson

  1. 0:00 Build this app
  2. 0:38 An empty folder
  3. 1:14 One round
  4. 1:52 Listen to the page
  5. 2:27 See each mistake
  6. 3:11 Measure the time
  7. 3:48 Work out the speed
  8. 4:48 Remember your best
  9. 5:26 Give it a server
  10. 6:05 Send a round
  11. 6:38 Save the score
  12. 7:12 Bring it back
  13. 7:56 Run the built app
  14. 8:32 Stop the server
  15. 9:18 What you built

This lesson builds Type Sprint, a typing test, starting from an empty folder. Type a wrong letter and the page marks it red. Fix it, finish the passage, and you get your speed. Reload, and your best is still there. Open a second browser, and your score is on a leaderboard there too.

So the app has three parts: a page, a store inside your browser, and a server. All three are JavaScript, and you’ll write every one. At the end you’ll stop the server while you’re in the middle of a round and see what still works.

You need Node, which comes with npm. Every file below is the whole file, and every command was run with Node 25, npm 11, Vite 8, TypeScript 7 and Oxlint 1.

An empty folder

Make a folder called type-sprint and open a terminal in it. npm init -y writes a package.json. Change its "type" from "commonjs" to "module", so Node treats every .js file as a module, and install three tools as dev dependencies:

npm init -y
npm install --save-dev vite typescript oxlint

Vite serves the page while you work and builds it at the end. TypeScript and Oxlint, a linter, check the code. Here is package.json as it ends up, with the scripts this lesson adds along the way:

{
  "name": "type-sprint",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "vite",
    "server": "node server.js",
    "test": "node --test src/*.test.js",
    "check": "npm test && oxlint src server.js vite.config.js && tsc --noEmit",
    "build": "npm run check && vite build"
  },
  "devDependencies": {
    "oxlint": "^1.93.0",
    "typescript": "^7.0.2",
    "vite": "^8.3.8"
  }
}

The page is index.html: a name, a Start button inside a form, a place for the passage, a box to type in, three numbers, a status line and the leaderboard.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Type Sprint</title>
    <link rel="stylesheet" href="/src/style.css">
  </head>
  <body>
    <main>
      <h1>Type Sprint</h1>
      <form id="start-form">
        <label>Name <input id="name" maxlength="20" required></label>
        <button>Start</button>
      </form>
      <p id="passage"></p>
      <label for="typing">Type the passage</label>
      <textarea id="typing" rows="4" disabled></textarea>
      <p>Time <output id="time">0.0 s</output></p>
      <p>This round <output id="this-round">–</output></p>
      <p>Your best <output id="best">–</output></p>
      <p id="status" role="status"></p>
      <section>
        <h2>Top ten rounds</h2>
        <button id="refresh" type="button">Refresh</button>
        <ol id="scores"></ol>
      </section>
    </main>
    <script type="module" src="/src/main.js"></script>
  </body>
</html>

src/style.css colors the letters. A wrong letter is underlined as well as red, so it shows without color:

body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; }
#passage { font-family: ui-monospace, monospace; font-size: 1.25rem; line-height: 1.6; }
.correct { color: #1a7f37; }
.wrong { color: #cf222e; text-decoration: underline; }
textarea { width: 100%; font: inherit; }

The passage lives in its own module, src/passage.js. It is exactly 150 characters long, spaces and punctuation included:

export const passage = "Rain taps the window as the last train leaves. A tired orange cat sleeps beside a blue bag, and the lights of the small city slide away into the dark.";

Run npm run dev and open the address Vite prints, http://127.0.0.1:5173/. The page is there, but nothing on it works yet.

One round

A round has to remember five things: the passage, the player’s name, when the round started, when it ended, and what’s been typed so far. That’s a class, in src/round.js:

export class Round {
  constructor(text, name, startedAt) {
    this.text = text;
    this.name = name;
    this.startedAt = startedAt;
    this.endedAt = null;
    this.typed = "";
  }

  update(value, now) {
    if (this.endedAt !== null) return;
    this.typed = value;
    if (value === this.text) this.endedAt = now;
  }

  elapsed(now) {
    return (this.endedAt ?? now) - this.startedAt;
  }
}

The ending time starts as null, because nobody has finished yet. update takes the typed text and the current time. When the text matches the passage exactly, it records the ending time, and after that it ignores every call. elapsed gives the time so far, or the whole round’s time once it has ended.

A test pins that down. Node has a test runner built in, so no package is needed. This is src/round.test.js:

import { test } from "node:test";
import assert from "node:assert/strict";
import { Round } from "./round.js";

test("a round ends only when the text matches", () => {
  const round = new Round("Rain", "Ada", 1000);
  round.update("Raim", 2000);
  assert.equal(round.endedAt, null);
  round.update("Rain", 31000);
  assert.equal(round.endedAt, 31000);
  round.update("Rai", 40000);
  assert.equal(round.typed, "Rain");
  assert.equal(round.elapsed(50000), 30000);
});

The script

Everything that happens on the page is in src/main.js. Here is the whole file. The sections after it go through it part by part.

import { passage } from "./passage.js";
import { Round } from "./round.js";
import { wordsPerMinute } from "./score.ts";

const startForm = document.querySelector("#start-form");
const nameInput = document.querySelector("#name");
const passageBox = document.querySelector("#passage");
const typing = document.querySelector("#typing");
const time = document.querySelector("#time");
const thisRound = document.querySelector("#this-round");
const bestOutput = document.querySelector("#best");
const status = document.querySelector("#status");
const scoreList = document.querySelector("#scores");
const refresh = document.querySelector("#refresh");

const BEST_KEY = "type-sprint-best";
const UNAVAILABLE = "Leaderboard unavailable. Your result is still here.";

const letters = [...passage].map((character) => {
  const span = document.createElement("span");
  span.textContent = character;
  return span;
});
passageBox.append(...letters);

let round = null;

function paint() {
  const typed = round ? round.typed : "";
  letters.forEach((span, i) => {
    const reached = i < typed.length;
    span.classList.toggle("correct", reached && typed[i] === passage[i]);
    span.classList.toggle("wrong", reached && typed[i] !== passage[i]);
  });
}

function tick(active) {
  if (round !== active || active.endedAt !== null) return;
  time.textContent = `${(active.elapsed(performance.now()) / 1000).toFixed(1)} s`;
  setTimeout(() => tick(active), 100);
}

function readBest() {
  try {
    return JSON.parse(localStorage.getItem(BEST_KEY));
  } catch {
    return null;
  }
}

function showBest() {
  const best = readBest();
  bestOutput.textContent = best ? `${best.wpm} WPM` : "–";
}

function saveBest(result) {
  const best = readBest();
  if (best && best.wpm >= result.wpm) return;
  try {
    localStorage.setItem(BEST_KEY, JSON.stringify(result));
  } catch {
    // Storage can be full or blocked; the round still counts on this page.
  }
}

let latestRequest = 0;

function paintScores(scores) {
  scoreList.replaceChildren();
  for (const score of scores) {
    const item = document.createElement("li");
    item.textContent = `${score.name}: ${score.wpm} WPM`;
    scoreList.append(item);
  }
}

async function loadScores() {
  const request = ++latestRequest;
  try {
    const response = await fetch("/api/scores");
    if (!response.ok) throw new Error(`Status ${response.status}`);
    const scores = await response.json();
    if (request === latestRequest) paintScores(scores);
    status.textContent = "";
  } catch {
    if (request === latestRequest) status.textContent = UNAVAILABLE;
  }
}

async function sendRound(finished) {
  const request = ++latestRequest;
  try {
    const response = await fetch("/api/scores", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        name: finished.name,
        text: finished.typed,
        elapsedMs: finished.elapsed(),
      }),
    });
    if (!response.ok) throw new Error(`Status ${response.status}`);
    const scores = await response.json();
    if (request === latestRequest) paintScores(scores);
    status.textContent = "";
  } catch {
    if (request === latestRequest) status.textContent = UNAVAILABLE;
  }
}

function finish(finished) {
  typing.disabled = true;
  const elapsedMs = finished.elapsed();
  const wpm = wordsPerMinute(passage.length, elapsedMs);
  time.textContent = `${(elapsedMs / 1000).toFixed(1)} s`;
  thisRound.textContent = `${wpm} WPM`;
  saveBest({ wpm, elapsedMs });
  showBest();
  sendRound(finished);
}

startForm.addEventListener("submit", (event) => {
  event.preventDefault();
  round = new Round(passage, nameInput.value.trim(), performance.now());
  typing.value = "";
  typing.disabled = false;
  typing.focus();
  thisRound.textContent = "–";
  paint();
  tick(round);
});

typing.addEventListener("input", () => {
  if (round === null || round.endedAt !== null) return;
  round.update(typing.value, performance.now());
  paint();
  if (round.endedAt !== null) finish(round);
});

refresh.addEventListener("click", loadScores);

showBest();
loadScores();

Listen to the page

The Start button sits inside a form, so the script listens for the form’s submit event. A form’s submit loads the page again, so event.preventDefault() comes first. Then the listener creates a new Round, empties the typing box and puts the cursor in it.

A second listener waits for input on the box. That event fires on every edit: a typed letter, a deletion, even a paste. Each time, the listener hands the box’s text and the current time to round.update. It does nothing when there’s no round, or when the round has finished.

See each mistake

To color the passage letter by letter, every letter needs an element of its own. [...passage] spreads the passage into an array of characters, and map turns each one into a span, with the character set by textContent. The spans are kept in letters, so the fourth span and the fourth character typed share an index. The passage is plain ASCII, so the array’s indexes and the string’s agree. A passage with emoji would need more care, because most emoji are two characters of a JavaScript string.

paint walks the spans and compares each with what was typed. classList.toggle takes a class name and a boolean: a match gets correct, a mismatch gets wrong, and a letter not reached yet gets neither. The input listener calls paint after every edit.

Measure the time

performance.now() returns a timestamp in milliseconds. The round reads it when Start is pressed and again when the last letter matches. Subtract, and that’s how long the round took.

The number ticking on the page is a separate job. tick writes the time so far, then uses setTimeout to run itself again a tenth of a second later. A timer can run late, so the round never counts its callbacks: they only redraw the number. tick stops when the round ends or a new round replaces it, which is why it checks round !== active.

Work out the speed

Typing speed is counted in words per minute, and the usual rule treats every five characters as one word, spaces and punctuation included. The passage’s 150 characters are 30 words. Typed in 30 seconds, half a minute, that’s 60 words per minute. As a function, in src/score.ts:

export function wordsPerMinute(characters: number, elapsedMs: number): number {
  if (elapsedMs <= 0) return 0;
  return Math.round((characters / 5) / (elapsedMs / 60000));
}

It’s the one TypeScript file in the project, so both inputs are declared as numbers. It doesn’t touch the page or read a clock: two numbers go in and one comes out, which makes it easy to test. src/score.test.js checks the example:

import { test } from "node:test";
import assert from "node:assert/strict";
import { wordsPerMinute } from "./score.ts";

test("150 characters in 30 seconds is 60 WPM", () => {
  assert.equal(wordsPerMinute(150, 30000), 60);
});

npm test runs both test files:

> test
> node --test src/*.test.js

✔ a round ends only when the text matches
✔ 150 characters in 30 seconds is 60 WPM
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 64

The test imports score.ts straight from Node. Node removes the type annotations and runs what’s left. It doesn’t check the types: that’s the type checker’s job, in the build below.

Remember your best

A reload throws the page away, and every variable with it. So the best result lives in localStorage, under the key type-sprint-best. localStorage only holds strings, so saveBest turns the record into text with JSON.stringify, and readBest parses it back when the page loads. Both sit in try and catch: storage can be blocked or full, and a broken value shouldn’t stop the page.

localStorage belongs to one browser, and to one origin: the scheme, the host and the port. A second browser has its own, and so does another address on the same computer.

Give it a server

A leaderboard needs one place every browser can reach. That’s server.js, in the project’s root:

import { createServer } from "node:http";
import { readFile, readdir, writeFile } from "node:fs/promises";
import { passage } from "./src/passage.js";
import { wordsPerMinute } from "./src/score.ts";

const scoreFile = new URL("./scores.json", import.meta.url);
const dist = new URL("./dist/", import.meta.url);
const MAX_BODY = 4096;
const TYPES = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css" };

async function loadScores() {
  try {
    return JSON.parse(await readFile(scoreFile, "utf8"));
  } catch (error) {
    if (error.code === "ENOENT") return [];
    throw error;
  }
}

// The built page: an explicit list of files, never the project folder.
async function builtFiles() {
  const files = new Map();
  try {
    files.set("/", "index.html");
    for (const name of await readdir(new URL("assets/", dist))) {
      files.set(`/assets/${name}`, `assets/${name}`);
    }
  } catch {
    files.clear();
  }
  return files;
}

let scores = await loadScores();
const built = await builtFiles();
let saving = Promise.resolve();

function reply(response, status, body) {
  response.writeHead(status, { "Content-Type": "application/json" });
  response.end(JSON.stringify(body));
}

function validate(body) {
  if (body === null || typeof body !== "object") return null;
  const name = typeof body.name === "string" ? body.name.trim() : "";
  if (name.length < 1 || name.length > 20) return null;
  if (body.text !== passage) return null;
  const { elapsedMs } = body;
  if (typeof elapsedMs !== "number" || !(elapsedMs > 0) || elapsedMs > 3600000) return null;
  return { name, wpm: wordsPerMinute(body.text.length, elapsedMs) };
}

function receive(request, response) {
  let body = "";
  let tooBig = false;
  request.setEncoding("utf8");
  request.on("data", (chunk) => {
    body += chunk;
    if (body.length > MAX_BODY && !tooBig) {
      tooBig = true;
      reply(response, 413, { error: "Body too large" });
    }
  });
  request.on("end", () => {
    if (tooBig) return;
    let score;
    try {
      score = validate(JSON.parse(body));
    } catch {
      score = null;
    }
    if (score === null) return reply(response, 400, { error: "Invalid score" });

    saving = saving.then(async () => {
      const next = [...scores, score]
        .sort((a, b) => b.wpm - a.wpm)
        .slice(0, 10);
      await writeFile(scoreFile, JSON.stringify(next, null, 2));
      scores = next;
      reply(response, 201, scores);
    }).catch(() => reply(response, 500, { error: "Could not save score" }));
  });
}

createServer(async (request, response) => {
  const path = new URL(request.url, "http://127.0.0.1").pathname;
  if (path === "/api/scores" && request.method === "GET") return reply(response, 200, scores);
  if (path === "/api/scores" && request.method === "POST") return receive(request, response);
  const file = request.method === "GET" ? built.get(path) : undefined;
  if (file === undefined) return reply(response, 404, { error: "Not found" });
  const type = TYPES[file.slice(file.lastIndexOf("."))] ?? "application/octet-stream";
  response.writeHead(200, { "Content-Type": type });
  response.end(await readFile(new URL(file, dist)));
}).listen(8000, "127.0.0.1", () => {
  console.log("Listening on http://127.0.0.1:8000");
});

When a browser asks for GET /api/scores, the server answers with its array as JSON. And it imports wordsPerMinute from the same score.ts the page uses. The function never touched the page, so it runs in Node unchanged.

Run it with npm run server. While you work, Vite serves the page on port 5173 and Node answers on port 8000. vite.config.js tells Vite to pass every request under /api on to Node:

export default {
  server: {
    host: "127.0.0.1",
    port: 5173,
    strictPort: true,
    proxy: { "/api": "http://127.0.0.1:8000" },
  },
};

Send a round

When the passage is finished, the page sends a POST to /api/scores with three things: the name, the text that was typed, and the time it took. Not the speed. The server reads the body in chunks with data events, waits for end, and parses it. Then it checks everything: the name has to be 1 to 20 characters once trimmed, the text has to be the passage, and the time has to be a number above zero and at most an hour. Only then does it work out the speed itself.

Every bad value gets a 400 and leaves the list alone. A body over 4,096 characters gets a 413 and isn’t parsed. The time still comes from the browser, though, so anyone can send a fast one: this is a practice board, not proof of anyone’s speed.

Save the score

The server adds the new score, sorts the list with b.wpm - a.wpm so the higher speed comes first, keeps the first ten, and writes the list to scores.json. It replies 201 with the updated list only after the write has finished. An array lives in memory, and memory is gone when Node stops; with the file, the server reads its scores back when it starts.

Those lines sit inside saving = saving.then(...). Two writes to one file must not overlap, so each save waits for the one before it, and reads the list only when its turn comes. Without the chain, two rounds finished at the same moment could each sort the old list and the second write would drop the first score. With it, twelve rounds sent at once all landed in the right top ten. When a write fails, the server answers 500, keeps the last list that reached the disk, and the next save can still run.

scores.json is read once, at startup. A missing file starts an empty list. A file that isn’t valid JSON stops the server instead of being written over.

Bring it back

Back in the page, sendRound awaits the response, checks response.ok, then awaits its JSON: the top ten. paintScores clears the old list and creates one list item per score. It sets each item’s text with textContent, so a name full of HTML tags, such as <b>Ada</b>, shows its brackets as plain text instead of turning bold. The same function draws the board when the page loads and when Refresh is pressed.

If the server doesn’t answer at all, fetch rejects and the await throws, so both requests sit in try and catch, and the page shows a message beside the board. A refresh that fails keeps the old list. One detail: an older reply that arrives late shouldn’t paint over a newer one, so every request takes a number from latestRequest, and only the latest may paint.

Run the built app

npm run build runs the checks first, the tests, the linter and the type checker, then Vite packs the page into dist. tsconfig.json points the type checker at score.ts alone:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "strict": true,
    "noEmit": true,
    "types": []
  },
  "include": ["src/score.ts"]
}
> build
> npm run check && vite build


> check
> npm test && oxlint src server.js vite.config.js && tsc --noEmit


> test
> node --test src/*.test.js

✔ a round ends only when the text matches (0.313917ms)
✔ 150 characters in 30 seconds is 60 WPM (0.246125ms)
ℹ tests 2
ℹ suites 0
ℹ pass 2
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 71.808125
vite v8.3.8 building client environment for production...
transforming...
✓ 8 modules transformed.
rendering chunks...
computing gzip size...
dist/index.html                 1.05 kB │ gzip: 0.51 kB
dist/assets/index-BAVssXmQ.css  0.26 kB │ gzip: 0.20 kB
dist/assets/index-B5ogRSpp.js   3.64 kB │ gzip: 1.50 kB

✓ built in 357ms

Now stop Vite and start Node again. Node serves the built page and its assets from a fixed list, never the project folder, and answers the API itself, so one program runs the whole app at http://127.0.0.1:8000/. That’s a new origin, so its localStorage starts empty: your best from port 5173 isn’t there. The leaderboard is the same file.

Stop the server

Start a round, type half the passage, and stop Node with Ctrl+C. Keep typing. The letters still turn green, because that comparison runs in the page. Finish, and your speed appears, because wordsPerMinute runs in the page too. Your best is saved, because localStorage belongs to the browser. Only the leaderboard needed the server: its request fails, the catch runs, and the page says Leaderboard unavailable. Your result is still here. Start Node again and press Refresh, and the board comes back from scores.json with every score from before.

That round was never sent again. Each part does its own job, so when one part fails, only that part stops.

Your turn

The round typed while the server was down never reached the board. Make the page keep a round whose request failed, and send it again when the server answers. Where would you keep it so it survives a reload, and what stops it being sent twice?

Summary

  • A class holds the round’s state, and events feed it: submit starts a round, input hands it every edit.
  • One span per letter, compared by index, gives the red and green.
  • performance.now() measures the round; setTimeout only redraws the clock.
  • A pure function works out the speed, so it can be tested, type-checked, and imported by both the page and the server.
  • localStorage keeps your best in the browser; a Node server keeps the board in a file every browser can reach.
  • npm run build checks the code and builds dist, which Node serves along with the API.
  • Stop the server, and only the leaderboard stops.
Video transcript

Build this app

This is the JavaScript app we're about to build, starting from an empty folder. Type a wrong letter, and the page marks it red. Fix it, finish the passage, and you get your speed. Reload, and your best is still there. Open a second browser, and your score is on the leaderboard there too. So the app has three parts: a page, a store inside your browser, and a server. All three are JavaScript, and we'll write every one. Then, at the end, we'll stop the server while you're in the middle of a round. Will you lose that round? Not if each part does its own job. First, the empty folder.

An empty folder

The folder is called type-sprint, and there's nothing in it. Run npm init, and now it has a package dot json. Install three tools: Vite, which serves the page while we work, plus TypeScript and a linter to check our code. Then write the page: a name, a Start button, the passage, a box to type in, and three numbers for the time, this round and your best. Run npm run dev and open the address Vite prints. The page is there. But there's no JavaScript behind it yet, so nothing on it works.

One round

Start with the data. One round has to remember five things: the passage, the player's name, when the round started, when it ended, and what's been typed so far. So write a class called Round. Its constructor stores all five, and the ending time starts as null, because nobody has finished yet. The class gets one method, update, which takes the typed text and the current time. If the text matches the passage exactly, update records the ending time. After that, update ignores every call. But nothing on the page creates a Round yet.

Listen to the page

So connect the page. The Start button sits inside a form, so listen for the form's submit event. Call preventDefault first, or the browser loads the page again. Then create a new Round, empty the typing box and put the cursor in it. A second listener waits for input on that box. That event fires on every edit: a typed letter, a deletion, even a paste. Each time, the listener hands the box's text and the current time to round dot update. Now the round knows everything you type. But you can't see any of it.

See each mistake

To color the passage letter by letter, every letter needs an element of its own. So spread the passage into an array of characters, and map each character to a span on the page. Keep the spans in an array. Now the fourth span and the fourth character you typed share an index. A function called paint walks the spans and compares each one with what you typed. A match gets the class correct. A mismatch gets wrong. A letter you haven't reached gets neither. Call paint after every input. Type an M where the passage has an N, and that letter turns red. Go back, type N, and the same span turns green. But the app still can't tell you how fast you were.

Measure the time

Speed needs a time, and the browser has a clock for that: performance dot now, which returns a timestamp in milliseconds. Read the clock when Start is pressed, and again when the last letter matches. Subtract, and that's how long the round took. The number ticking on the page is a separate job. A small function writes the time so far, then uses setTimeout to run itself again a tenth of a second later. But a timer can run late, so we never count its callbacks. They only redraw the number. So now we have a duration: thirty seconds, for example. That's still not a typing speed.

Work out the speed

Typing speed is counted in words per minute, and the usual rule treats every five characters as one word. Our passage has a hundred and fifty characters, so that's thirty words. Type them in thirty seconds, half a minute, and your speed is sixty words per minute. As a function: characters divided by five, divided by the minutes that passed, rounded with Math dot round. Look at what this function doesn't do. It doesn't touch the page or read a clock. Two numbers go in, and one comes out. It's the one TypeScript file in the project, with both inputs declared as numbers. A function like that is easy to test: one line says a hundred and fifty characters in thirty thousand milliseconds must give sixty. Run npm test, and the line passes. The function also sits in a file of its own, which will matter when we get to the server. Finish a round now, and the page shows your speed. Reload, though, and the number is gone.

Remember your best

A reload throws the page away, and every variable with it. So your best has to live outside the page, in localStorage. When a round beats your best, save a small record: the speed and the time, turned into text with JSON dot stringify, because localStorage only holds strings. When the page loads, read the record back and parse it. Now finish a good round and reload. The round is gone, but your best comes back. Only in this browser, though. A different browser has never heard of you. A leaderboard needs one place that every browser can reach.

Give it a server

That place is a Node server, in one more JavaScript file: server dot js. The server keeps the scores in an array, each one a name and a speed. When a browser sends a GET request to slash API slash scores, the server answers with that array as JSON. Every browser that reaches the server gets the same list. And the scoring function in its own file? The server imports that same file. The function never touched the page, so it runs in Node unchanged. One function, two programs. Right now, though, the list is empty. Nobody has sent the server a score.

Send a round

So when you finish the passage, the page sends one, in a POST request to the same address. The body is JSON with three things: your name, the text you typed, and the time you took. No speed. On the server, the body arrives in chunks, so collect them, wait for the end event, and parse the text. Then check everything. The name has to be short. The text has to match the passage. The time has to be a positive number. Only then does the server work out the speed itself, with the function it imported.

Save the score

Add the new score to the list. Sort the list with a comparison function that puts the higher speed first, and keep the first ten. Then write the list to a file, scores dot json, and reply only after the write has finished. The reply carries the status two-oh-one and the updated list. Why a file? An array lives in memory, and memory is gone when Node stops. With the file, the server reads its scores back when it starts again. So the score is saved. But the page hasn't done anything with the reply.

Bring it back

Back in the page, await the response, check that its status is OK, then await its JSON. That's the top ten, as an array. Clear the old list and loop over the array, creating one list item per score. Set each item's text with textContent, so a name full of HTML tags shows up as plain text. The same function draws the board when the page loads, and when you press Refresh. So open the second browser again, and your score is there. One question is left. What if the server doesn't answer at all? Then the await throws. So wrap the request in try and catch, and show a message beside the board. We've written that catch. We haven't seen it run.

Run the built app

So far, Vite has served the page and passed our API requests on to Node. That's a setup for working on the app. To finish, run npm run build. First our script runs the checks: the test, the linter and the type checker. Then Vite packs the page into a folder called dist. Now stop Vite. Node serves the files in dist and answers the API, so a single program runs the whole app. Open Node's address and play a round. Everything works. Which brings us back to the question from the start of this video.

Stop the server

Start a round and type half the passage. Now stop Node. The server is gone, and the page doesn't know. Keep typing. The letters still turn green, because that comparison runs in the page. Finish the passage, and your speed appears, because the scoring function runs in the page too. Your best is saved, because localStorage belongs to the browser. Only the leaderboard needed the server. Its request fails, the catch finally runs, and the message says the leaderboard is unavailable. Nothing else broke. Start Node again and press Refresh. The board is back, with every score from before, read from the file. That's why each part got its own job. When one part fails, only that part stops.

What you built

So that's the whole app. A class holds the round. Events feed it. One function works out the speed, in the page and on the server. The browser keeps your best, and Node keeps the board. One round never reached that board: the one you typed while the server was down. Sending it again when the server is back is a good first feature to build yourself. This was the last video of Learn JavaScript. Every part of this app has its own video in that series, and the next step is coming up on screen.

Learn more