Practical Roadmap

Web Development

Build an accessible, responsive application, understand its data, and test the behaviour before sharing it.

Before You Begin

  • A computer with a modern browser
  • A text editor
  • No programming experience required

What You Will Build

A small resource-library application with accessible forms, saved data, tested interactions, and a clear README.

YOUR COURSE PROJECT · 10 CONNECTED STAGES

Build LearningShelf

Grow a small resource library from an HTML page into a local application with combined filtering, an accessible submission form, a validated API and PostgreSQL persistence. Each lesson adds to the same project; the completed source includes a reproducible run guide and verification record.

What You Need

  • A modern browser with developer tools
  • A text editor
  • Git from Track Your Changes with Git
  • A supported Node.js release from Load Data and Handle Failure
  • A local PostgreSQL installation and the pg driver from Model and Query Persistent Data

Set Up Your Project

  1. Create a separate folder named LearningShelf for your exercise. Do not edit the Hacktronian platform's files while following this roadmap.
  2. Begin with index.html and notes.md. Add styles.css, app.js and later server/database files only when their lessons introduce them.
  3. Use fixed starter IDs mdn, odin, fcc, academy and bandit when the JavaScript collection grows to five resources; assign web to the first three and security to the last two. Each record has id, title, url, topic and notes.
  4. Direct-file opening is sufficient for the early static lessons. From the data-loading lesson onward, run node serve.mjs and use http://127.0.0.1:4300 consistently. Ctrl+C in that terminal stops your local server.
  5. PostgreSQL is an additional setup in the database lesson, not a hidden prerequisite for the first page. Use a disposable local database and keep its connection credentials outside source control.

Markdown file · all lessons, examples and project steps · no account needed

01

Make Your First Page

Create LearningShelf's first HTML page and learn how document structure becomes browser content. Start with meaningful headings and resource links before adding styling or behavior.

What You Will Learn

  • Describe the different jobs of HTML, CSS and JavaScript.
  • Create a complete HTML document with meaningful headings and links.
  • Connect a local file change to an observable browser result.

Understand the Idea

A web page begins as a text file. The browser reads HTML and builds a document containing elements such as headings, paragraphs and links. An element has meaning: an h1 names the page's main topic, while an anchor with an href provides navigation. Choose elements for those jobs rather than for the size or color they happen to display.

Every LearningShelf page will have a head and a body. The head contains information about the document, including its title, character encoding and mobile viewport. The body contains the material a visitor reads and operates. Indentation helps you see which elements belong inside other elements; it does not create the nesting. Matching opening and closing tags does.

Start with content before visual polish. LearningShelf is a directory of resources you want to revisit. A visitor should be able to tell what it contains, read a resource name and follow its link. Make link text describe the destination instead of repeating 'click here'. Organize related content beneath headings so the structure remains understandable even without styling.

Save the file as index.html, not index.html.txt, and open it in a browser. At this stage a file address is sufficient because there is no data fetching or persistent browser state. Keep the editor and browser side by side: change one sentence, save, reload and check the result. Later lessons introduce a local server when the application needs an HTTP origin.

WORKED EXAMPLE

A Complete First Document

Create index.html in an empty LearningShelf folder. This example has no dependencies and can be opened directly in a modern browser. The resource links require internet only when you follow them.

html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>LearningShelf - My Resource Library</title>
</head>
<body>
  <header><h1>LearningShelf</h1><p>A small library for learning the web.</p></header>
  <main>
    <h2>My Resources</h2>
    <ul id="resource-list">
      <li><a href="https://developer.mozilla.org/en-US/curriculum/">MDN Curriculum</a><p>Start with web foundations.</p></li>
      <li><a href="https://www.theodinproject.com/">The Odin Project</a><p>Learn by building projects.</p></li>
      <li><a href="https://portswigger.net/web-security">Web Security Academy</a><p>Study web security in provided labs.</p></li>
    </ul>
  </main>
  <footer><p>Built while learning HTML.</p></footer>
</body>
</html>
  1. The language and encoding describe how the document should be interpreted.
  2. The title names the browser tab; h1 is the heading inside the page.
  3. The list groups resources, and each anchor names its own destination.

Expected Result

The browser shows a heading, three resource links with descriptions, and a footer. Tab moves through the links in document order.

PROJECT STAGE 01 / 10

Create the LearningShelf Skeleton

Builds on: A new empty project folder; no previous code is required.

  1. Create a folder named LearningShelf and an index.html file. Copy the example, save it, and open that exact file in your browser.
  2. Replace the introductory sentence with your own learning goal. Keep one h1 and add a second h2 section explaining who the collection is for.
  3. Add a locally created image named shelf.png only after the file exists. Give it alternative text describing useful information, or empty alt text if it is purely decorative.
  4. Use Tab and Enter to visit each link. Check the browser tab title and compare the heading order with the source.
  5. Create notes.md with three observations: an edit you predicted correctly, a mistake you corrected, and a question for the next lesson.

Keep This Deliverable

index.html, optional shelf.png, and notes.md containing a working first page and your observations.

Check Your Build

  • All three links have meaningful names and correct destinations.
  • You can identify the head, body and main heading in your file.
  • Reloading shows your latest saved sentence.

Common Mistakes and Fixes

The browser displays an older version of the page.
Check that the editor saved the same file whose path appears in the browser address bar.
An image shows a broken placeholder.
Check the filename, extension and relative path; do not add an image reference before creating its file.

Check Your Understanding

Why does changing the title element not change the large heading inside the page?

Reveal the explanation

The title is document metadata used for places such as the browser tab. The visible heading is separate body content, represented here by h1. Change each element according to its purpose.

Ready to Move On?

Explain the document structure, follow every link with the keyboard and show a saved edit after reload.

Open the learning resource
02

Give It a Responsive Layout

Give the existing LearningShelf resource list a flexible layout. Use the box model, a narrow-first grid and deliberate checks with long content, zoom and keyboard focus.

What You Will Learn

  • Explain the box model and why text containers need flexible space.
  • Use a narrow-first layout that adds columns when space permits.
  • Test content variations and browser zoom instead of relying on one screenshot.

Understand the Idea

CSS selects elements and assigns presentation rules to them. A declaration such as color changes one property; a selector determines which elements receive that declaration. Keep LearningShelf's content in index.html and put its presentation in styles.css. Linking the stylesheet in the head makes that separation visible and avoids repeating style decisions on every resource.

Think of each element as a box containing content, padding, a border and an outer margin. With border-box sizing, a declared width includes padding and border. This makes a card easier to reason about. Text still needs room to grow, so avoid fixed heights on descriptions and cards. A longer resource title should increase the height rather than overlap the next item.

A responsive layout adapts to the available space. Begin with one column, which naturally fits a narrow viewport. Add a second column only when there is enough room for readable cards. A media query responds to viewport conditions; it is not a list of phone models. The max-width on the page keeps lines manageable on a large monitor while flexible side spacing protects small screens.

Test the layout with real variations: a long title, an extra sentence, a narrow window and 200% browser zoom. Zoom can reduce the effective layout space, which is why it reveals rigid assumptions. Check the keyboard focus indicator against the chosen colors. A polished color scheme does not compensate for clipped text or an invisible focused link.

WORKED EXAMPLE

A Flexible Resource Grid

Create styles.css with these rules and add <link rel="stylesheet" href="styles.css"> inside index.html's head. Reload the page after saving both files.

css
* { box-sizing: border-box; }
body { margin: 0; font: 1rem/1.6 system-ui, sans-serif; color: #13251e; background: #f3f2ec; }
header, main, footer { width: min(100% - 2rem, 64rem); margin-inline: auto; }
#resource-list { display: grid; gap: 1rem; padding: 0; list-style: none; }
#resource-list > li { padding: 1rem; border: 1px solid #66776e; overflow-wrap: anywhere; }
a { color: #075b40; }
a:focus-visible { outline: 3px solid #075b40; outline-offset: 4px; }
img { max-width: 100%; height: auto; }
@media (min-width: 48rem) {
  #resource-list { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
  1. The page wrapper leaves space at the edges but stops growing at a readable width.
  2. The grid has one implicit column until the media query introduces two equal columns.
  3. Wrapping and flexible height allow long content to remain inside its card.

Expected Result

Cards stack on a narrow window and form two columns on a wider window. Their heights expand when descriptions become longer.

PROJECT STAGE 02 / 10

Make LearningShelf Readable at Different Sizes

Builds on: The HTML document and resource list from the first lesson.

  1. Add the stylesheet link and copy the example rules into styles.css. Confirm a visible change after reloading before adding more rules.
  2. Resize the browser slowly from a narrow window to a wide one. Identify the point where the media query changes the grid.
  3. Replace one resource title temporarily with a much longer title and add two description sentences. Fix any overlap without setting a fixed card height.
  4. Zoom to 200%, move through the links with Tab, and check that the focus outline remains visible and content remains reachable.
  5. Record your checks in notes.md, then restore realistic resource copy while retaining the layout improvements.

Keep This Deliverable

A linked styles.css and notes describing narrow, wide, long-content and zoom checks.

Check Your Build

  • Cards have no clipped text or overlapping controls.
  • The page remains usable at 200% zoom.
  • You can explain which rule controls the column change.

Common Mistakes and Fixes

The stylesheet appears to have no effect.
Check its relative filename in the link element and use browser developer tools to look for a failed CSS request.
A card is visually neat until its title becomes longer.
Remove rigid heights or truncation that hide required content; let the box grow and wrap text.

Check Your Understanding

Why is testing a long title useful even if your current titles are short?

Reveal the explanation

The layout must support content changes and different reading conditions. A long title exposes fixed-size assumptions before a later resource or larger text setting makes the page unusable.

Ready to Move On?

The same content remains readable at narrow widths and 200% zoom, and you can explain the grid's breakpoint.

Open the learning resource
03

Add a Small Interaction

Turn LearningShelf's fixed resource collection into a searchable directory. Keep the source data intact, combine query and topic conditions, and show clear result feedback.

What You Will Learn

  • Separate the original resource collection from the currently displayed results.
  • Combine search and category conditions deliberately.
  • Trace an input event through filtering to safe DOM updates.

Understand the Idea

JavaScript adds behavior to the document. Store resource records in an array, where each object describes one resource using consistent fields: id, title, url, topic and notes. Keep stable IDs that do not depend on the current array position. The original array is the source collection; a filtered array is a temporary view derived from it.

A filter answers a yes-or-no question for each resource. The title matches when it contains the normalized query, and the topic matches when the selected value is 'all' or equals the resource's topic. Both conditions must be true. Lowercasing and trimming the query make ordinary variations predictable, but they do not change the original resource titles.

Connect a search input's input event and a select's change event to the same updateResults function. That function should read both controls, derive the matching records and render them. Keeping the pipeline in one place prevents one control from accidentally ignoring the other. An empty query should match every title; a no-results view should explain what happened.

Build DOM nodes with createElement and assign labels through textContent. Do not assemble user-derived titles as HTML strings. An anchor's URL needs a separate protocol decision because text safety does not make every URL safe. For this fixed starter dataset use known HTTPS destinations; the form lesson will validate new URLs. Include a result-count message outside the list so a blank list is not the only feedback.

WORKED EXAMPLE

One Predictable Filter Function

Put this function in app.js. It has no browser dependency, so the example call also runs in a browser console. The later rendering function consumes its returned array.

javascript
function filterResources(items, query, topic) {
  const normalizedQuery = query.trim().toLowerCase();
  return items.filter(item => {
    const matchesText = item.title.toLowerCase().includes(normalizedQuery);
    const matchesTopic = topic === "all" || item.topic === topic;
    return matchesText && matchesTopic;
  });
}
const exampleResources = [
  { id: "mdn", title: "MDN Curriculum", topic: "web" },
  { id: "academy", title: "Web Security Academy", topic: "security" }
];
console.log(filterResources(exampleResources, " WEB ", "security"));
  1. Normalization makes surrounding spaces and uppercase letters irrelevant to this search.
  2. filter creates a new matching collection without deleting records from the original array.
  3. The final AND requires both text and category conditions to match.

Expected Result

The example logs an array containing only the Web Security Academy record. The original two-item array remains unchanged.

PROJECT STAGE 03 / 10

Add Combined Search and Topic Filtering

Builds on: The responsive resource list and its existing card appearance.

  1. Add visible labels, a search input with id search, and a select with id topic containing all, web and security values. Add a paragraph with id result-count and aria-live="polite".
  2. Create app.js and load it with a script element using defer. Define five records with the agreed fields and replace the hardcoded list with a renderResources function.
  3. In renderResources, create a list item and anchor for each record, set the label with textContent, append the nodes, and update the count or no-results message.
  4. Add updateResults to read both controls, call filterResources and pass the result to renderResources. Register both event listeners, then call updateResults once at startup.
  5. Try an empty query, mixed-case text, an unknown word and every category. Clear both controls and verify that all five records return.

Keep This Deliverable

A five-resource directory with combined filtering, result feedback and a notes.md truth table of tested inputs.

Check Your Build

  • Switching filters never permanently removes a record.
  • Both controls affect the same derived result.
  • No matches produces an explanatory message.

Common Mistakes and Fixes

Clearing the filter does not restore every resource.
Filter the original collection each time; do not replace it with the filtered result.
The count and cards disagree.
Derive both from the same result array during one render operation.

Check Your Understanding

What should filterResources return for an empty query and topic 'all', and why?

Reveal the explanation

It should return all input records. Every string includes the empty query, and the 'all' topic makes the category condition true. The original collection remains available for later searches.

Ready to Move On?

Clearing controls restores all records, both filters work together, and no results produces useful feedback.

Open the learning resource
04

Track Your Changes with Git

Record the working LearningShelf prototype in local Git history. Review staged changes, make a focused improvement on a branch and document how the current version runs.

What You Will Learn

  • Distinguish working files, staged changes and commits.
  • Record small changes whose purpose you can explain.
  • Use a branch and reviewed diff without publishing the project.

Understand the Idea

Git records snapshots of selected project content. Your working folder is where edits happen; the staging area is the proposed content of the next commit; a commit records that staged snapshot with a message. Saving a file in the editor does not create a commit. Staging one file does not automatically stage every other changed file.

Start version control now with the working LearningShelf you already understand. The first commit is a baseline from which later changes can be compared. Create README.md before that commit so the baseline explains how to open the page and which features currently exist. A reader should not need access to this chat to identify the project's entry point.

Use a branch for a small improvement such as clarifying the empty state. Inspect git diff before staging, then inspect git diff --staged before committing. The two commands answer different questions: what has changed but is not staged, and what would be included in the next commit? Include only files relevant to the change.

Git is local unless you deliberately connect and push to a remote service. This lesson requires no GitHub account and publishes nothing. Do not commit credentials, private notes or later dependency folders. A .gitignore prevents ordinary accidental inclusion of matching untracked paths, but it does not remove a secret that is already in history; prevention and review still matter.

WORKED EXAMPLE

Record a Small, Reviewable Change

Run these commands in a terminal whose current directory is LearningShelf after creating README.md and .gitignore. This block records the initial baseline only. If Git requests author identity, configure your chosen name and email for this repository before committing; the branch improvement is a separate project task.

text
git init
git status
git add index.html styles.css app.js README.md .gitignore
git diff --staged
git commit -m "Add searchable LearningShelf prototype"
git show --stat HEAD
  1. Explicit filenames make the staged scope visible instead of including every untracked file.
  2. Inspect the staged diff before running the commit command, and stop if it includes an unintended change.
  3. git show inspects the resulting local commit; none of these commands uploads the project.

Expected Result

The repository contains a baseline commit. git status identifies any content that remains untracked or uncommitted.

PROJECT STAGE 04 / 10

Give LearningShelf a Reproducible History

Builds on: The working five-resource app, HTML, stylesheet and notes from the first three lessons.

  1. Install Git if needed and open a terminal inside LearningShelf. Use a directory-listing command to confirm that index.html is in the current folder before initializing.
  2. Write README.md with the purpose, current file layout, direct-file opening instructions and the filtering checks you have completed.
  3. Create .gitignore with .env, node_modules/ and personal-notes/ on separate lines. Keep personal material outside the committed project rather than relying on naming alone.
  4. Create the baseline commit using the example sequence. If you included shelf.png, review and stage that intended asset separately as well.
  5. Run git switch -c improve-empty-state, edit and verify the empty-state message, then inspect git diff. Stage app.js, inspect git diff --staged, commit the improvement and explain both snapshots with git log --oneline and git show.

Keep This Deliverable

A local Git repository, README.md, .gitignore and two understandable commits.

Check Your Build

  • You can identify which content is staged before committing.
  • The README describes the current way to run the app.
  • No remote publication or credential file is required.

Common Mistakes and Fixes

A commit contains an unrelated file.
Inspect the staged diff and unstage unintended paths before committing; do not use a broad add command without reviewing its scope.
You think a successful commit uploaded the website.
A local commit records history on this computer. Remote sharing is a separate operation and is not part of this lesson.

Check Your Understanding

You edit app.js after staging it. Which version would a commit record?

Reveal the explanation

The staged version is recorded, not the later unstaged edit. Inspect both git diff and git diff --staged, then stage the newer change only if you intend to include it.

Ready to Move On?

Explain working, staged and committed content using your own repository, with a README that matches the current app.

Open the learning resource
05

Build Forms People Can Use

Add a labeled resource form to LearningShelf. Validate the draft, preserve useful input after errors and describe the current in-memory storage limit honestly.

What You Will Learn

  • Connect visible labels and correction instructions to form controls.
  • Validate a resource before adding it to the collection.
  • Preserve a user's work when one field needs correction.

Understand the Idea

A form translates a visitor's intention into structured data. Give LearningShelf fields for title, URL, topic and notes. Each control needs a visible label associated through matching for and id values. Placeholder text disappears during typing and is not a substitute for a label. Use a native submit button so keyboard interaction follows browser conventions.

Validation has two jobs here: helping a person correct a mistake and protecting the resource model from unexpected values. Use HTML constraints such as required and type="url" for immediate feedback, then normalize and check the data in JavaScript. For this exercise accept only HTTP or HTTPS links and the two known topic values. A syntactically valid URL can still use a scheme you do not want.

Keep the draft separate from the accepted collection. Read fields when the form submits, trim the title, validate the URL and topic, then construct a new resource with a stable ID. If validation fails, show a useful message and preserve the entered values. Reset the form only after the resource has actually been accepted into the current in-memory collection.

At this stage newly submitted resources exist only while the page remains loaded. State that limitation honestly instead of claiming they were permanently saved. The later server and database lessons examine other storage boundaries. Browser checks improve usability, but a shared service must repeat validation on its own side because requests can arrive without using your form.

WORKED EXAMPLE

Validate a Draft before Accepting It

Add this pure helper to app.js and call it from the form submit handler. It returns normalized fields or throws an explanation; the caller decides how to display the error.

javascript
function normalizeDraft(input) {
  const title = String(input.title ?? "").trim();
  if (!title || title.length > 120) throw new Error("Use a title between 1 and 120 characters.");
  const url = new URL(String(input.url ?? ""));
  if (!["http:", "https:"].includes(url.protocol)) throw new Error("Use an HTTP or HTTPS link.");
  if (!["web", "security"].includes(input.topic)) throw new Error("Choose web or security.");
  return { title, url: url.href, topic: input.topic, notes: String(input.notes ?? "").trim().slice(0, 500) };
}
console.log(normalizeDraft({ title: "  MDN  ", url: "https://developer.mozilla.org/", topic: "web", notes: "Reference" }));
  1. The helper checks the title before constructing a resource.
  2. URL parses the address; the protocol allowlist is a separate rule.
  3. The returned object contains only supported fields, ready for a caller to add an ID.

Expected Result

The example returns a trimmed title, normalized HTTPS URL, web topic and notes. Unsupported schemes or topics are rejected instead of becoming clickable resource entries.

PROJECT STAGE 05 / 10

Let a Learner Add a Resource

Builds on: The filtered resource collection, render function and local Git history.

  1. Add a form with visible labels and matching IDs for title, URL, topic and notes. Add required, maxlength and appropriate input types, plus a paragraph for submission feedback.
  2. Write a submit listener that prevents navigation, reads FormData and calls normalizeDraft inside try/catch. Convert a URL parsing failure into a clear instruction to enter a complete HTTP or HTTPS address.
  3. On success, add a resource with a stable unique ID to the original array and rerun updateResults. Explain if active filters hide the newly added resource.
  4. On failure, preserve all field values, identify the field that needs correction and move focus deliberately when that helps. Reset fields only after success.
  5. Test keyboard submission, an empty title, an unsupported URL scheme and a valid resource. Reload once to observe the current in-memory limitation, then document it.

Keep This Deliverable

An accessible resource form with validation, honest feedback and a recorded failure test.

Check Your Build

  • Labels remain visible while typing.
  • An invalid submission does not erase correct fields.
  • The feedback distinguishes an in-memory addition from permanent storage.

Common Mistakes and Fixes

Any URL accepted by the browser becomes a resource link.
Parse the address and restrict protocols explicitly; input type alone does not express every application rule.
A failed submission clears all fields.
Leave the draft untouched until validation and acceptance succeed.

Check Your Understanding

If the browser rejects an empty title, why will the server still need a title check later?

Reveal the explanation

A request can be sent directly without using this form or its JavaScript. The server must enforce its own data rules at the boundary it controls; browser validation is helpful feedback, not that enforcement.

Ready to Move On?

Invalid input preserves correct fields, a valid draft is added to the source collection, and feedback does not claim permanent storage.

Open the learning resource
06

Load Data and Handle Failure

Serve LearningShelf locally and load its starter collection from JSON. Distinguish request status, parsing and data validation, with visible loading and retry behavior.

What You Will Learn

  • Serve local files through an HTTP origin before fetching JSON.
  • Represent loading, success, empty and failure as different states.
  • Check both the HTTP response and the shape of its data.

Understand the Idea

Fetching data introduces time and failure into a page that previously used an immediately available array. The request may still be pending, the server may return an error, or the response may contain something other than your resource records. Treat these as explicit states instead of assuming that an empty list always means no resources exist.

Move the starter collection into resources.json, using double-quoted property names and no comments or trailing commas. JSON is a data format, not a JavaScript program. Serve LearningShelf through http://127.0.0.1:4300 because file-address behavior is not a reliable basis for browser requests. The server runs on your own computer; serving localhost does not publish the project.

A fulfilled fetch promise does not necessarily mean the request succeeded. A response such as 404 still gives you a Response object, so inspect response.ok before parsing JSON. Parsing can fail independently. After parsing, check that the value is an array and that every record has the fields your renderer uses. A valid JSON object containing an error message is not a valid resource list.

Keep one load function responsible for setting status, replacing the source collection and refreshing results. Disable Retry while a request is active and preserve the current search controls. Add a clear message if loading fails, rather than clearing the interface silently. A retry should repeat the request deliberately; rendering a card should never trigger another data load.

WORKED EXAMPLE

A Small Local File Server

Save this complete example as serve.mjs beside index.html. Install a supported Node.js release, open a terminal in LearningShelf, run node serve.mjs, and visit http://127.0.0.1:4300. Leave the terminal running; Ctrl+C stops this server.

javascript
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
const files = {
  "/": ["index.html", "text/html; charset=utf-8"],
  "/styles.css": ["styles.css", "text/css; charset=utf-8"],
  "/app.js": ["app.js", "text/javascript; charset=utf-8"],
  "/resources.json": ["resources.json", "application/json; charset=utf-8"],
  "/shelf.png": ["shelf.png", "image/png"]
};
createServer(async (request, response) => {
  let pathname;
  try { pathname = new URL(request.url, "http://127.0.0.1:4300").pathname; }
  catch { response.writeHead(400).end("Invalid request URL"); return; }
  const file = files[pathname];
  if (request.method !== "GET" || !file) {
    response.writeHead(404).end("Not found");
    return;
  }
  try {
    const body = await readFile(new URL(file[0], import.meta.url));
    response.writeHead(200, { "Content-Type": file[1] }).end(body);
  } catch {
    response.writeHead(500).end("Could not read the requested local file");
  }
}).listen(4300, "127.0.0.1");
  1. The allowlist serves only named project files, not arbitrary filesystem paths.
  2. File URLs resolve relative to serve.mjs, so launching from another folder does not change the asset location.
  3. The listening address is loopback-only; the server is an exercise tool, not a production hosting configuration.

Expected Result

The local URL serves the same page through HTTP. Opening /resources.json displays your JSON, while an unlisted path returns 404.

PROJECT STAGE 06 / 10

Load LearningShelf's Starter Collection

Builds on: The rendered collection, form and filter pipeline, plus a supported local Node.js installation.

  1. Create resources.json from the five original records and add serve.mjs from the example. Start the server, open the loopback URL, and use that URL consistently from this point onward.
  2. In app.js replace the initial populated array with an empty mutable collection. Add a loadResources async function that fetches ./resources.json, checks response.ok, parses the body and validates the expected array and record fields.
  3. Add a loading message and a Retry button. On success assign the validated collection and call updateResults; on failure show a correction-oriented message. Disable Retry during each attempt and enable it afterward.
  4. Temporarily try an empty array, invalid JSON and a renamed JSON file. Observe each request in the Network panel, restore the file, and confirm Retry recovers.
  5. Document the new node serve.mjs command and local URL in README.md. Explain that form additions still exist only in browser memory until the server persistence lessons.

Keep This Deliverable

resources.json, serve.mjs and a loading interface with deliberate success, empty, failure and retry behavior.

Check Your Build

  • A 404 and malformed JSON show useful errors.
  • An empty valid array is distinguished from a failed load.
  • Restoring the fixture and pressing Retry recovers without losing search settings.

Common Mistakes and Fixes

A 404 response is parsed as though it were the expected resource array.
Check response.ok before parsing, then validate the parsed value separately.
Fetching works differently when opening index.html directly.
Use the stable loopback URL from the running server; do not build the request flow around file-address behavior.

Check Your Understanding

Why can loading fail after response.ok is true?

Reveal the explanation

The response can contain malformed JSON or valid JSON with the wrong structure. Transport status, parsing and application data validation are separate checks.

Ready to Move On?

Empty data, missing files and malformed JSON produce distinct outcomes, and Retry recovers after the fixture is restored.

Open the learning resource
07

Understand the Server Boundary

Move resource acceptance into a local GET/POST API. Validate direct requests, return deliberate status codes and keep storage behind functions that the database lesson can replace.

What You Will Learn

  • Explain which rules a browser can bypass and a server must enforce.
  • Define a small GET/POST API with deliberate error responses.
  • Separate request validation from resource storage so persistence can change later.

Understand the Idea

The browser is one client of a service, not the authority over shared data. A person can change its JavaScript or send a request directly. Move acceptance of new resources into the local server so the same rules apply regardless of which interface sends the request. Keep the browser checks because they still make mistakes easier to correct.

Add an /api/resources route before the static-file lookup in serve.mjs. GET returns the current collection; POST accepts one draft and returns the accepted record with a server-generated ID. Other methods receive 405, while unknown routes remain 404. A malformed JSON body or invalid field should produce a 400 response with a useful public message.

Read request bodies with an explicit size limit, such as 16 KiB for this small exercise, and reject larger bodies with 413. Require application/json for POST and return 415 for unsupported media types. These boundaries make the example predictable. Avoid sending stack traces or configuration details back to the browser when an unexpected server error occurs.

Keep storage behind two functions named listResources and insertResource. For this lesson they use an in-memory array initialized from resources.json. That array survives a page reload but disappears when the server process restarts. Naming this limitation prepares you for the database lesson and prevents a temporary prototype from falsely promising permanent storage.

WORKED EXAMPLE

Validate on the Server

This is a focused helper, not a complete API server. Save it as validate-resource.mjs and import it from serve.mjs. Call it only after parsing a bounded JSON request body; the route assigns a new ID afterward.

javascript
export function validateResource(input) {
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Send a resource object.");
  if (typeof input.title !== "string" || !input.title.trim() || input.title.trim().length > 120) throw new Error("Use a title between 1 and 120 characters.");
  if (typeof input.url !== "string") throw new Error("Provide a complete URL.");
  let url;
  try { url = new URL(input.url); } catch { throw new Error("Provide a complete URL."); }
  if (!["http:", "https:"].includes(url.protocol)) throw new Error("Use an HTTP or HTTPS link.");
  if (!["web", "security"].includes(input.topic)) throw new Error("Choose a supported topic.");
  if (input.notes !== undefined && (typeof input.notes !== "string" || input.notes.length > 500)) throw new Error("Keep notes within 500 characters.");
  return { title: input.title.trim(), url: url.href, topic: input.topic, notes: input.notes?.trim() ?? "" };
}
  1. The server checks actual types instead of trusting the browser's conversion.
  2. Only allowed fields are returned, so a client cannot choose a trusted internal ID through this helper.
  3. The route should map validation failures to 400 and unexpected internal failures to a generic 500.

Expected Result

A valid draft returns a normalized record without an ID. Arrays, unsupported topics and non-HTTP(S) links are rejected before reaching storage.

PROJECT STAGE 07 / 10

Move Resource Acceptance behind an API

Builds on: serve.mjs, the loading function and form from earlier lessons; Node's built-in HTTP, filesystem and crypto modules are sufficient.

  1. Add listResources and insertResource functions above the handler, backed by the starter array. After validation, have the POST route generate a randomUUID from node:crypto and pass that complete record to insertResource; reject a duplicate normalized URL with a deliberate conflict response.
  2. Implement GET /api/resources and POST /api/resources before the static allowlist. For POST inspect Content-Type, count incoming body bytes, reject oversized input, parse JSON and call validateResource inside explicit error handling.
  3. Change loadResources to fetch /api/resources. Change the form to POST its draft as JSON, wait for an accepted response, then reload the collection and reset only after success.
  4. From a second terminal or a disposable Node script, send a POST with an unsupported topic and confirm 400. Send a valid draft and confirm 201 plus a server-assigned ID, even without using the form.
  5. Reload the page to see the server's memory survive, then stop and restart the server to observe its limit. Record the API contract and temporary storage behavior in README.md.

Keep This Deliverable

A local read-and-create API that independently validates drafts and a browser interface that waits for the server's response.

Check Your Build

  • Direct invalid requests cannot bypass the server's rules.
  • A failed POST preserves the form draft.
  • The README states that server memory is lost on restart.

Common Mistakes and Fixes

The interface says 'Added' before the request finishes.
Wait for a successful server response before resetting fields or displaying success.
Unexpected request fields are copied directly into storage.
Build the accepted record from validated fields and generate trusted metadata on the server.

Check Your Understanding

Why put storage behind functions if the first version is just an array?

Reveal the explanation

The request handler should depend on the operations it needs rather than a particular storage container. The next lesson can replace those operations with database queries without changing the API contract.

Ready to Move On?

A direct invalid request is rejected, successful creation returns a server-generated ID, and server-memory limits are documented.

Open the learning resource
08

Model and Query Persistent Data

Add PostgreSQL as an explicit local learning setup. Replace the API's in-memory storage with parameterized database operations and verify that accepted resources survive a restart.

What You Will Learn

  • Model resource data with stable keys and useful constraints.
  • Use query parameters for values instead of constructing SQL from input.
  • Verify persistence by restarting the application and reading the same records.

Understand the Idea

A database gives resource data a lifetime beyond the current server process. Create a disposable local PostgreSQL database named learningshelf and connect only to that learning database. Each resource becomes a row; columns describe its fields. A primary key identifies a row even if its title changes, while a unique constraint can prevent two rows from storing the same normalized URL.

Constraints express rules at the storage boundary. A non-null title does not by itself reject an empty string, so a check can require trimmed content. A topic check restricts rows to the supported values. The application still validates requests to provide helpful feedback, while the database protects its own invariants if another writer reaches it.

Pass user-controlled values separately from SQL text. The node-postgres driver uses placeholders such as $1 and an array of parameter values. A title containing an apostrophe remains a value instead of changing the structure of the query. Parameterization does not replace permission checks, field validation or a decision about which queries the application exposes.

Replace the two storage functions from the previous lesson and keep the API shape stable. Start with an empty table and add resources through your validated form, which exercises the full browser-to-database path. Database connection settings belong in the server environment, never in app.js or committed source. This teaching example creates a table at startup; a maintained production app would use deliberate versioned migrations.

WORKED EXAMPLE

A Small PostgreSQL Storage Module

First install PostgreSQL and create a disposable database named learningshelf. In the project terminal run npm init -y, then npm install pg. Save this complete module as database.mjs. In PowerShell set $env:LEARNINGSHELF_DATABASE_URL = 'postgresql://YOUR_LOCAL_USER:YOUR_LOCAL_PASSWORD@127.0.0.1:5432/learningshelf', replacing the placeholders locally, then start node serve.mjs after importing these functions there. Do not commit a real connection URL.

javascript
import pg from "pg";
const connectionString = process.env.LEARNINGSHELF_DATABASE_URL;
if (!connectionString) throw new Error("Set LEARNINGSHELF_DATABASE_URL for the local learning database.");
const pool = new pg.Pool({ connectionString });
await pool.query(`CREATE TABLE IF NOT EXISTS resources (
  id text PRIMARY KEY,
  title text NOT NULL CHECK (length(trim(title)) BETWEEN 1 AND 120),
  url text NOT NULL UNIQUE,
  topic text NOT NULL CHECK (topic IN ('web', 'security')),
  notes text NOT NULL DEFAULT ''
)`);
export async function listResources() {
  const result = await pool.query("SELECT id, title, url, topic, notes FROM resources ORDER BY title, id");
  return result.rows;
}
export async function insertResource(resource) {
  const result = await pool.query(
    "INSERT INTO resources (id, title, url, topic, notes) VALUES ($1, $2, $3, $4, $5) RETURNING id, title, url, topic, notes",
    [resource.id, resource.title, resource.url, resource.topic, resource.notes]
  );
  return result.rows[0];
}
  1. The connection URL is read only by the Node process, and a missing setting stops setup clearly.
  2. The INSERT statement keeps SQL structure separate from the five values.
  3. Both functions return the same data shape the API used before; ORDER BY makes the list's ordering deliberate.

Expected Result

Accepted resources are stored in PostgreSQL and remain after restarting Node. A duplicate URL violates the database's unique constraint rather than silently creating a second identical link.

PROJECT STAGE 08 / 10

Give LearningShelf Persistent Storage

Builds on: The validated API and its listResources/insertResource boundary, plus a local PostgreSQL installation.

  1. Create the disposable learningshelf database through PostgreSQL's tools and verify the intended database before running schema code. Install pg, keep package-lock.json, and retain node_modules/ in .gitignore.
  2. Add database.mjs from the example and set the server-only environment variable using your shell's syntax. Keep real credentials out of README examples, source files and AI prompts.
  3. Replace the in-memory storage functions with imports. Ensure the API awaits them and supplies the normalized record plus its server-generated ID to insertResource.
  4. Map PostgreSQL's duplicate-key error to a clear 409 response for an existing URL. Keep other database failures generic to the browser while recording enough local information to diagnose them.
  5. Add five resources through the form, restart Node, and confirm all five return. Use a database client to select one topic with a parameterized or prepared query, and record the result without exposing connection credentials.

Keep This Deliverable

A database-backed local resource API, its schema and dependency lockfile, plus a restart-persistence check.

Check Your Build

  • Resources survive a Node restart.
  • An apostrophe in a title is stored as data.
  • Duplicate URLs produce clear feedback and preserve the draft.

Common Mistakes and Fixes

The application silently connects to an unintended default database.
Require an explicit local connection setting and verify the target before running the learning schema.
A query builds SQL by concatenating the submitted title.
Keep the SQL text fixed and pass values through the driver's parameter array.

Check Your Understanding

Why are both request validation and a database constraint useful for a title?

Reveal the explanation

Request validation provides contextual feedback before storage. A database constraint protects the table's invariant even if data arrives through a different writer. They enforce related rules at different boundaries.

Ready to Move On?

Accepted resources persist after restarting Node, duplicate URLs receive clear feedback, and query values are passed as parameters.

Open the learning resource
09

Test Behaviour and Edge Cases

Test LearningShelf's actual filter helper, then check the UI, API and persistence separately. Prove that a focused regression case catches a deliberate filter bug.

What You Will Learn

  • Write checks for observable behavior and meaningful edge cases.
  • Separate pure-function tests from browser and API checks.
  • Demonstrate that a regression check fails for the bug it is meant to catch.

Understand the Idea

A test is useful when it tells you that something a user depends on changed unexpectedly. Begin with the filter because it has simple inputs and outputs. The expected result should come from the requirement, not from copying the implementation into a test. Include an ordinary case, an empty query and a query that matches text in the wrong category.

Move filterResources into filter.mjs and export it so both the browser and a Node test can use the same implementation. Load app.js as a module and add filter.mjs to the local server's explicit file list. Modules make this dependency visible; duplicating the function in a test would allow the application and test copies to disagree.

Use Node's built-in test runner for these pure checks, then test the whole journey in the browser. The function tests cannot prove that the form has a label, that a request succeeds or that records persist. Add a manual checklist covering search, invalid submission, successful submission, reload and server restart. Record actual outcomes and the conditions used.

Prove the test's value by temporarily changing the filter's AND to OR on a disposable branch. At least the category-sensitive case should fail. Restore the implementation and rerun. When a real bug is discovered, write a similarly focused regression check before repairing it. Browser automation can be added later without replacing keyboard and visual observations.

WORKED EXAMPLE

Test the Actual Filter Function

Save this as filter.test.mjs beside the exported filter.mjs from the previous interaction lesson. Run node --test filter.test.mjs from LearningShelf. This example tests data behavior and does not open a browser.

javascript
import test from "node:test";
import assert from "node:assert/strict";
import { filterResources } from "./filter.mjs";
const items = [
  { id: "mdn", title: "MDN Curriculum", topic: "web" },
  { id: "academy", title: "Web Security Academy", topic: "security" }
];
test("combines normalized text with the selected topic", () => {
  assert.deepEqual(filterResources(items, " WEB ", "security").map(item => item.id), ["academy"]);
  assert.deepEqual(filterResources(items, "MDN", "security"), []);
});
test("empty controls restore all resources without mutating input", () => {
  assert.deepEqual(filterResources(items, "", "all"), items);
  assert.equal(items.length, 2);
});
  1. The test imports the production helper instead of recreating its logic.
  2. The wrong-category case catches an accidental OR that would admit an otherwise matching title.
  3. Assertions describe expected values, and a failing assertion produces a non-successful test run.

Expected Result

The correct filter passes both tests. Changing its combined condition to OR makes the wrong-category assertion fail.

PROJECT STAGE 09 / 10

Create a Small Verification Suite

Builds on: The complete local UI, validated API and persistent database from the previous lessons.

  1. Extract the existing filter into filter.mjs without changing its behavior. Import it from app.js, change the script tag to type="module", and allow the module's path in serve.mjs.
  2. Create filter.test.mjs from the example and run it. Add a no-matches test whose expected array you can explain from the input.
  3. On a disposable branch, introduce the AND-to-OR bug, observe the meaningful failure and restore the correct implementation. Record the failure reason rather than only the final green result.
  4. Create checks.md with a keyboard-only search and submission journey, including an invalid URL and duplicate URL. Verify failure messages and that valid draft values are retained.
  5. Add persistence and server-failure checks: restart Node to verify stored resources, then stop it to observe how the page reports a failed request. Restore the server before finishing.

Keep This Deliverable

A tested shared filter module, a reproducible regression demonstration and an honest browser/API checklist.

Check Your Build

  • Tests exercise the application's actual helper.
  • The deliberate bug produces the expected failure.
  • Manual results distinguish completed checks from untested behavior.

Common Mistakes and Fixes

A passing unit test is described as proof that the entire app works.
Name its scope and complement it with checks of the UI, API and storage boundaries.
The test passes even when the application function is broken.
Ensure it imports the real implementation and does not duplicate or mock away the behavior under test.

Check Your Understanding

Why can every filter test pass while submitting the form still fails?

Reveal the explanation

The filter tests cover a pure function. Form markup, event wiring, request validation, database access and feedback are separate parts of the journey that those tests do not exercise.

Ready to Move On?

The correct filter passes, the planned AND-to-OR regression fails, and browser checks record observed results.

Open the learning resource
10

Review and Prepare a Release

Prepare a reproducible local LearningShelf release. Document its browser, Node and PostgreSQL parts, review actual verification evidence and separate packaging from publication.

What You Will Learn

  • Prepare instructions that let another learner reproduce the project.
  • Review functionality, data behavior and configuration before calling a version ready.
  • Distinguish a local release package from a decision to publish a running service.

Understand the Idea

A release is a particular version that another person can run and evaluate. Begin from a known working commit, run the checks and read the interface as a new learner would. Replace temporary messages, repair broken local assets and verify the main journey on a narrow window. Record limitations honestly rather than hiding them behind a general claim that everything is tested.

LearningShelf now has different kinds of files. The browser needs HTML, CSS and client modules. Node needs serve.mjs, server validation and database code. PostgreSQL stores the records. Explain these roles in README.md so someone does not expect the full application to run by opening index.html directly or uploading only static files.

Document the environment setting by name with a clearly fictional example, but never include a real connection password. Explain how to create a disposable database, install dependencies from the lockfile, start the server and run tests. For existing data, describe how the owner should back up their own database before destructive experimentation; do not package private records with the project.

Measure an actual performance concern before optimizing. An oversized local image is a good first candidate because its request size and visual result are easy to compare. Preserve readability and interactions. Publishing remains a separate action: this local app needs a Node runtime and PostgreSQL if deployed, whereas Hacktronian's learning pages can be distributed as static files.

WORKED EXAMPLE

A Reproducible Release Checklist

Save a version of this checklist as RELEASE-CHECKLIST.md and fill in actual results. It is a documentation template rather than an executable command; replace every bracketed placeholder with a truthful observation.

text
LearningShelf Release
Commit: [exact commit identifier]
Run: npm ci, set LEARNINGSHELF_DATABASE_URL, then node serve.mjs
Address: http://127.0.0.1:4300
Tests: node --test filter.test.mjs

[ ] Search and topic filters combine correctly.
[ ] Invalid and duplicate submissions preserve the draft.
[ ] Accepted resources remain after a server restart.
[ ] All controls work with the keyboard.
[ ] Narrow layout and 200% zoom remain usable.
[ ] Server failure produces clear feedback.
[ ] No credentials, private records or dependency folder are packaged.
Known limitations: [specific limitations and checks not completed]
Data location: local PostgreSQL database named learningshelf
  1. The commit identifies the exact code associated with the verification record.
  2. The run instructions name the database requirement and stable local origin.
  3. The limitations field distinguishes known boundaries from completed checks.

Expected Result

A reader receives an auditable release note with commands, data behavior, verification scope and remaining limitations instead of an unsupported 'production-ready' label.

PROJECT STAGE 10 / 10

Hand LearningShelf to Another Learner

Builds on: The working database-backed project and checks from the previous lesson.

  1. Run the automated tests and main manual journey, then record the current commit and actual results in RELEASE-CHECKLIST.md. Leave incomplete checks marked incomplete.
  2. Rewrite README.md with prerequisites, filenames, database setup, environment-variable name, npm ci, startup URL and test commands. Include how to stop the local server.
  3. Inspect the files you intend to share. Exclude .env, personal notes, real database exports and node_modules; include package.json, the lockfile and the source needed to recreate the learning schema.
  4. Review one measured concern, such as a large image. Record the request size before and after an appropriate change and verify that the image still communicates the same information.
  5. Ask another learner to follow the README, or simulate a fresh setup in a separate disposable folder without relying on your memory. Correct missing instructions and commit the release notes.

Keep This Deliverable

A documented local release with source, dependency lockfile, checks, setup instructions and stated limits.

Check Your Build

  • The README explains both Node and PostgreSQL requirements.
  • The shared files contain no real credentials or personal records.
  • A fresh setup can reproduce the main journey using written instructions.

Common Mistakes and Fixes

A static upload is expected to run the Node API.
Explain the runtime boundaries. A static host serves browser files; the API and database need compatible services if you later choose to deploy.
The release notes list checks that were planned but never run.
Record only observed results and mark remaining checks explicitly as incomplete.

Check Your Understanding

What makes a release reproducible rather than merely a folder that worked on your computer?

Reveal the explanation

It identifies the code version, dependencies, configuration names, data setup, run commands and verification steps. Another person can follow those instructions and observe the same intended behavior without guessing hidden state.

Ready to Move On?

Another learner can follow written setup instructions, reproduce the main journey and understand the remaining limits.

Open the learning resource

Project References

HACKTRONIAN_CLI // COMMAND PALETTE
QUICK_EXEC: