EthicsComputerCourses
Join training +91 90532 10052

Enterprise SaaS Frontend

HTML · Lesson 219 of 234 Project 16 min read Updated

By the end of this project you will have built the front end of a software-as-a-service (SaaS) product: a marketing site, sign-in screens, an app shell with its own router, an onboarding wizard that saves drafts, a settings page, a web-component design system, English and Hindi, an offline shell, a strict security policy, a performance budget and a CI pipeline.

SaaS is software people use in the browser and pay for by subscription. Multi-tenant means one copy of the app serves many customers, called tenants, and each sees only its own data. Our product is VidyaDesk, a made-up school-management tool from Kochi built by Ananya Menon and Rohan Verma. Each school is a tenant with its own address, such as stmarys-kochi.vidyadesk.example.

What you should know first: Secure Authentication Form Design, History API, Shadow DOM Fundamentals, Design Systems & HTML Structure, Multilingual HTML Architecture, Offline HTML Applications, Trusted Types Fundamentals and Content Security Policy Advanced. This project combines them; it does not teach them again.

What you will build

PartAddressMain jobBuilt from
Marketing sitevidyadesk.example/Explain the product, rank in search, collect sign-upsStatic HTML, SEO, structured data
Sign-instmarys-kochi.vidyadesk.example/loginPasskey, password or SMS codeServer-rendered forms
App shell/app/...Header, navigation and a router that draws each viewHistory API, focus management
Onboarding/app/onboarding/1 to /3Set up a new school in three stepsWizard, progress, saved drafts
Settings/app/settingsEdit school detailsForms, unsaved-changes guard
Design system/design/Documented components every screen usesCustom elements, shadow DOM, tokens

E-Commerce Website Frontend builds a store and Admin Dashboard Frontend builds data tables and charts. This project builds the platform around such screens: who you are, which school you belong to, how you move between views, and how it all stays safe, fast and translated.

Step 1: Separate the marketing site from the app

A SaaS product is really two front ends, like a railway station. The booking hall is open to everyone and wants to be found. The platform is behind the ticket gate, for people who already have tickets.

QuestionMarketing siteApp shell
Who uses itVisitors, search engines, social previewsSigned-in staff of one school
How pages are madeStatic HTML built ahead of timeOne shell page; JavaScript draws views
Search enginesIndexed, with titles, canonical URLs and JSON-LDNever indexed
JavaScriptAlmost noneThe router, components and API calls
CachingCDN caches pages for everyoneShell cached; school data never shared

Keep them in separate folders and deploy them with separate settings:

Text
vidyadesk/
  marketing/            static pages: /, /pricing/, /schools/, /blog/
  app/
    index.html          the shell: header, nav, <main>, dialog
    app.js              router and views
    sw.js               service worker for the shell
    i18n/en.json, hi.json
  design/
    tokens.css          primitive and semantic tokens
    components/         vd-alert.js, vd-badge.js, vd-money.js, vd-steps.js
    index.html          the component library page

The server adds X-Robots-Tag: noindex to every /app/ response, so a leaked link never appears in search results. The marketing site gets the full work from Advanced Technical SEO.

Tenants. The subdomain tells the server which school to load. The front end only shows the school's name and brand colour; it never decides what data a user may see. The server checks every API call against the session, because anyone can edit JavaScript in DevTools.

Step 2: Auth screens outside the app

Keep sign-in as normal server-rendered pages, not routes inside the app. A plain POST form works before any JavaScript loads, password managers recognise it, and an app bug can never lock people out.

HTML
<main>
  <h1>Sign in to St Mary's School, Kochi</h1>
  <form method="post" action="/login">
    <label for="email">School email</label>
    <input id="email" name="email" type="email" autocomplete="username webauthn" required>

    <label for="password">Password</label>
    <input id="password" name="password" type="password" autocomplete="current-password" required>

    <input type="hidden" name="returnTo" value="/app/settings">
    <button>Sign in</button>
  </form>
  <p><a href="/login/code">Get a 6-digit code by SMS instead</a></p>
</main>

The webauthn token offers saved passkeys in the email field; the code page uses one autocomplete="one-time-code" field. Both are explained in Secure Authentication Form Design.

Two things are special in a multi-tenant app:

  • The session cookie. Name it __Host-session with Secure, HttpOnly, SameSite=Lax, Path=/ and no Domain. The browser refuses a __Host- cookie that breaks those rules, and the cookie stays on one exact host, so St Mary's session never reaches another school's subdomain. Never keep session tokens in localStorage, where injected script can read them.
  • The return address. The router sends signed-out users to /login?returnTo=/app/settings. An attacker could craft returnTo=https://evil.example and use your login page to forward people to a fake site. This is an open redirect. Accept only paths inside your app:
JavaScript
const ORIGIN = "https://stmarys-kochi.vidyadesk.example";

function safeReturnTo(value) {
  if (!value) return "/app";
  const url = new URL(value, ORIGIN);
  const ok = url.origin === ORIGIN && (url.pathname === "/app" || url.pathname.startsWith("/app/"));
  return ok ? url.pathname + url.search : "/app";
}

for (const input of ["/app/settings?tab=fees", "https://evil.example/app", "//evil.example/app",
                     "/\\evil.example/app", "javascript:alert(1)", "/apple-offer", null]) {
  console.log(String(input).padEnd(26), "->", safeReturnTo(input));
}
Output
/app/settings?tab=fees     -> /app/settings?tab=fees
https://evil.example/app   -> /app
//evil.example/app         -> /app
/\evil.example/app         -> /app
javascript:alert(1)        -> /app
/apple-offer               -> /app
null                       -> /app

new URL() catches what a startsWith("/") check misses: //evil.example and /\evil.example both point to another site. The server repeats the check, because it does the redirect.

Step 3: A design system of web components

Buttons, links and inputs stay native HTML styled with tokens, because native controls already work with forms and keyboards. Web components are kept for pieces with behaviour: an alert, a status badge, a rupee amount that follows the language, and the wizard's progress. The library rules:

  • Tokens are CSS custom properties. Primitives (--vd-teal-700) feed semantic tokens (--vd-brand). A tenant theme changes only semantic tokens, which cross the shadow boundary.
  • Parts. Each component exposes named parts, such as badge or bar, for careful overrides with ::part().
  • No inline styles, no HTML strings. Styles are constructable stylesheets shared by every instance (adoptedStyleSheets). Shadow markup comes from one Trusted Types policy, vd-static, which accepts only keys of a fixed template table.
  • Tenant colours are validated with CSS.supports("color", value), because a school admin typed them.

This library page runs under a CSP meta tag that enforces Trusted Types. Its documentation table is read from the component classes, so it cannot go out of date.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="Content-Security-Policy"
        content="require-trusted-types-for 'script'; trusted-types vd-static; object-src 'none'; base-uri 'none'">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>VidyaDesk design system</title>
  <style>
    :root {
      --vd-teal-700: #0f766e; --vd-green-100: #dcfce7; --vd-amber-100: #fef3c7;
      --vd-red-100: #fee2e2; --vd-blue-100: #e0f2fe; --vd-gray-900: #1f2937;
      --vd-brand: var(--vd-teal-700);
      --vd-radius: 8px;
      --vd-space: 8px;
      font-family: system-ui, "Noto Sans Devanagari", sans-serif;
      color: var(--vd-gray-900);
    }
    body { margin: 16px; max-width: 46rem; }
    section { margin-block: 20px; }
    vd-badge.big::part(badge) { font-size: 1.1rem; }
    table { border-collapse: collapse; width: 100%; }
    th, td { border: 1px solid #ccc; padding: 4px 8px; text-align: start; }
    button, select { font: inherit; }
  </style>
</head>
<body>
  <h1>VidyaDesk components</h1>
  <p>
    <label>School theme
      <select id="tenant">
        <option value="stmarys">St Mary's, Kochi</option>
        <option value="gurukul">Gurukul, Rohtak</option>
        <option value="broken">Broken value from the database</option>
      </select>
    </label>
    <button type="button" id="lang" lang="hi">हिन्दी</button>
  </p>
  <p id="theme-note" role="status"></p>

  <section aria-labelledby="h-alert">
    <h2 id="h-alert">vd-alert</h2>
    <vd-alert tone="success">Fees of ₹2,450 received from Aarav's parent.</vd-alert>
    <vd-alert tone="warning">Attendance for Class 7B is not marked yet.</vd-alert>
  </section>
  <section aria-labelledby="h-badge">
    <h2 id="h-badge">vd-badge</h2>
    <vd-badge>Active</vd-badge> <vd-badge tone="warning">Trial: 9 days left</vd-badge>
    <vd-badge class="big">Styled with ::part(badge)</vd-badge>
  </section>
  <section aria-labelledby="h-money">
    <h2 id="h-money">vd-money</h2>
    <p>Term fees collected: <vd-money amount="1825000"></vd-money></p>
  </section>
  <section aria-labelledby="h-steps">
    <h2 id="h-steps">vd-steps</h2>
    <vd-steps current="2">
      <ol><li>School details</li><li>Classes</li><li>Invite staff</li></ol>
    </vd-steps>
  </section>
  <section aria-labelledby="h-docs">
    <h2 id="h-docs">Generated documentation</h2>
    <table id="docs"><thead><tr><th>Element</th><th>Defined</th><th>Attributes</th><th>Parts</th></tr></thead><tbody></tbody></table>
    <p id="tt-check"></p>
  </section>

  <script>
    // 1. The only HTML strings the library may use, behind one Trusted Types policy
    const templates = {
      alert: '<div part="box" class="box"><span part="icon" class="icon" aria-hidden="true"></span><div><slot></slot></div></div>',
      badge: '<span part="badge" class="badge"><slot></slot></span>',
      money: '<data part="value"></data>',
      steps: '<p part="label" id="label"></p><progress part="bar" aria-labelledby="label"></progress><slot></slot>'
    };
    const tt = window.trustedTypes?.createPolicy ? window.trustedTypes : { createPolicy: (n, rules) => rules };
    const policy = tt.createPolicy("vd-static", {
      createHTML(key) {
        if (!Object.hasOwn(templates, key)) throw new TypeError("Unknown template: " + key);
        return templates[key];
      }
    });
    const sheet = (css) => { const s = new CSSStyleSheet(); s.replaceSync(css); return s; };
    const localeOf = (el) => (el.closest("[lang]")?.lang === "hi" ? "hi-IN" : "en-IN");

    // 2. A small base class: shadow root, shared styles, re-render on language change
    class VdElement extends HTMLElement {
      static parts = [];
      static observedAttributes = [];
      #onLocale = () => this.render();
      constructor() {
        super();
        const root = this.attachShadow({ mode: "open" });
        root.adoptedStyleSheets = [this.constructor.styles];
        root.innerHTML = policy.createHTML(this.constructor.template);
      }
      connectedCallback() { document.addEventListener("vd-localechange", this.#onLocale); this.render(); }
      disconnectedCallback() { document.removeEventListener("vd-localechange", this.#onLocale); }
      attributeChangedCallback() { if (this.isConnected) this.render(); }
      render() {}
    }

    customElements.define("vd-alert", class extends VdElement {
      static template = "alert"; static parts = ["box", "icon"]; static observedAttributes = ["tone"];
      static styles = sheet(`
        :host { display: block; margin-block: var(--vd-space); }
        .box { display: flex; gap: var(--vd-space); padding: var(--vd-space) calc(var(--vd-space) * 2);
               border-radius: var(--vd-radius); background: var(--bg, var(--vd-blue-100));
               border-inline-start: 4px solid var(--vd-brand); }
        :host([tone="success"]) { --bg: var(--vd-green-100); }
        :host([tone="warning"]) { --bg: var(--vd-amber-100); }
        :host([tone="danger"]) { --bg: var(--vd-red-100); }`);
      render() {
        const tone = this.getAttribute("tone") ?? "info";
        this.shadowRoot.querySelector(".icon").textContent = { success: "✓", warning: "!", danger: "×" }[tone] ?? "i";
        if (!this.hasAttribute("role")) this.setAttribute("role", tone === "danger" ? "alert" : "status");
      }
    });

    customElements.define("vd-badge", class extends VdElement {
      static template = "badge"; static parts = ["badge"]; static observedAttributes = ["tone"];
      static styles = sheet(`
        .badge { display: inline-block; padding: 2px 10px; border-radius: 999px;
                 background: var(--vd-brand); color: #fff; font-size: .875rem; }
        :host([tone="warning"]) .badge { background: #92400e; }`);
    });

    customElements.define("vd-money", class extends VdElement {
      static template = "money"; static parts = ["value"]; static observedAttributes = ["amount"];
      static styles = sheet(`[part="value"] { font-weight: 600; font-variant-numeric: tabular-nums; }`);
      render() {
        const amount = Number(this.getAttribute("amount"));
        const out = this.shadowRoot.querySelector("data");
        out.value = String(amount);
        out.textContent = new Intl.NumberFormat(localeOf(this),
          { style: "currency", currency: "INR", maximumFractionDigits: 0 }).format(amount);
      }
    });

    customElements.define("vd-steps", class extends VdElement {
      static template = "steps"; static parts = ["label", "bar"]; static observedAttributes = ["current"];
      static styles = sheet(`
        [part="label"] { margin: 0 0 4px; font-weight: 600; }
        progress { inline-size: 100%; accent-color: var(--vd-brand); }`);
      connectedCallback() {
        this.shadowRoot.querySelector("slot").addEventListener("slotchange", () => this.render());
        super.connectedCallback();
      }
      render() {
        const items = [...this.querySelectorAll("li")];
        const total = items.length;
        const current = Math.min(Math.max(Number(this.getAttribute("current")) || 1, 1), total || 1);
        items.forEach((li, i) => i === current - 1 ? li.setAttribute("aria-current", "step") : li.removeAttribute("aria-current"));
        this.shadowRoot.querySelector("#label").textContent =
          localeOf(this) === "hi-IN" ? `${total} में से चरण ${current}` : `Step ${current} of ${total}`;
        const bar = this.shadowRoot.querySelector("progress");
        bar.max = total || 1;
        bar.value = current;
      }
    });

    // 3. Tenant themes: validate before use
    const themes = { stmarys: "#0f766e", gurukul: "#9f1239", broken: "red; background: url(x)" };
    document.querySelector("#tenant").addEventListener("change", (event) => {
      const value = themes[event.target.value];
      const note = document.querySelector("#theme-note");
      if (CSS.supports("color", value)) {
        document.documentElement.style.setProperty("--vd-brand", value);
        note.textContent = "Brand colour set to " + value;
      } else {
        note.textContent = "Rejected brand colour: " + value;
      }
    });

    // 4. Language switch: components re-render themselves
    document.querySelector("#lang").addEventListener("click", (event) => {
      const hindi = document.documentElement.lang !== "hi";
      document.documentElement.lang = hindi ? "hi" : "en";
      event.target.lang = hindi ? "en" : "hi";
      event.target.textContent = hindi ? "English" : "हिन्दी";
      document.dispatchEvent(new Event("vd-localechange"));
    });

    // 5. Documentation generated from the registry
    for (const name of ["vd-alert", "vd-badge", "vd-money", "vd-steps"]) {
      const cls = customElements.get(name);
      const row = document.createElement("tr");
      for (const text of [name, cls ? "yes" : "no", cls?.observedAttributes.join(", ") ?? "", cls?.parts.join(", ") ?? ""]) {
        const cell = document.createElement("td");
        cell.textContent = text;
        row.append(cell);
      }
      document.querySelector("#docs tbody").append(row);
    }
    try {
      document.querySelector("#tt-check").innerHTML = "<b>raw string</b>";
      document.querySelector("#tt-check").textContent = "Trusted Types not enforced in this browser.";
    } catch (error) {
      document.querySelector("#tt-check").textContent = "Trusted Types enforced: innerHTML refused a plain string (" + error.name + ").";
    }
  </script>
</body>
</html>

You should see two alerts, three badges, ₹18,25,000, "Step 2 of 3" with a progress bar, the generated table, and a line saying Trusted Types refused a plain string. Choose Gurukul: badges, alert borders and the progress bar turn maroon. Choose the broken value: it is rejected. Press हिन्दी: the label becomes "3 में से चरण 2" without a reload.

Step 4: The app shell and its router

The shell is one page with a header, navigation, a <main> and a <dialog>. A router reads the address, finds the matching route (a path pattern plus a view function) and draws that view into <main>, like the sorting chart a dabbawala uses: each code maps to one destination. On every view change it does six jobs:

  1. Guard. Routes under /app need a session; otherwise go to /login?returnTo=... with replaceState(), so Back does not loop.
  2. Unsaved changes. If the settings form is dirty, ask in a <dialog> first.
  3. History. pushState() for a new view, replaceState() for redirects, popstate for Back and Forward.
  4. Render with createElement() and textContent, never HTML strings, so the code already obeys Trusted Types.
  5. Announce. Set document.title, update aria-current="page", and focus the new <h1> (which has tabindex="-1"), so screen readers read it as on a page load.
  6. Translate. Text comes from a message table through t(); numbers and dates from Intl.

The onboarding wizard saves a draft on every keystroke (never passwords or codes), so a principal who closes the laptop at step 2 continues later. Settings change live data, so they use a Save button and the leave guard instead. The Try-it editor cannot change its own address, so setUrl() catches that error and a fake address bar shows the URL, as in History API.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>VidyaDesk</title>
  <style>
    :root { --brand: #0f766e; font-family: system-ui, "Noto Sans Devanagari", sans-serif; }
    body { margin: 0; }
    #address { margin: 0; padding: 4px 8px; background: #eef; font: 13px monospace; }
    .skip { position: absolute; left: -999px; }
    .skip:focus { left: 8px; top: 8px; background: #fff; padding: 8px; }
    header { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; padding: 8px 16px; background: var(--brand); color: #fff; }
    header a, header button { color: inherit; font: inherit; }
    header button { background: transparent; border: 1px solid; border-radius: 4px; }
    nav { display: flex; gap: 12px; }
    nav a[aria-current="page"] { font-weight: bold; text-underline-offset: 5px; }
    main { padding: 16px; max-width: 36rem; }
    h1:focus { outline: 3px solid var(--brand); outline-offset: 4px; }
    label { display: block; margin-top: 12px; }
    input, select, button { font: inherit; min-height: 36px; }
    ol li[aria-current="step"] { font-weight: bold; }
    #offline { margin: 0; padding: 8px 16px; background: #fef3c7; }
  </style>
</head>
<body>
  <p id="address"></p>
  <a class="skip" href="#main" data-i18n="skip"></a>
  <header>
    <strong>VidyaDesk</strong>
    <nav id="nav" aria-label="App">
      <a href="/app" data-i18n="home" data-section="/app"></a>
      <a href="/app/onboarding/1" data-i18n="setup" data-section="/app/onboarding"></a>
      <a href="/app/settings" data-i18n="settings" data-section="/app/settings"></a>
    </nav>
    <button type="button" id="signout" data-i18n="signOut"></button>
    <button type="button" id="lang"></button>
  </header>
  <p id="offline" role="status" hidden></p>
  <main id="main"></main>
  <dialog id="leave" aria-labelledby="leave-title">
    <form method="dialog">
      <h2 id="leave-title" data-i18n="leaveTitle"></h2>
      <button value="stay" data-i18n="stay"></button>
      <button value="leave" data-i18n="leave"></button>
    </form>
  </dialog>

  <script>
    const ORIGIN = "https://stmarys-kochi.vidyadesk.example";
    const messages = {
      en: { skip: "Skip to content", home: "Home", setup: "Set up", settings: "Settings", signOut: "Sign out",
        signInTitle: "Sign in to St Mary's School", email: "School email", password: "Password", signIn: "Sign in",
        welcome: "Welcome back, {name}", fees: "Fees collected this term", due: "Next fee due date",
        "joined.one": "{count} new student joined this week", "joined.other": "{count} new students joined this week",
        setupTitle: "Set up your school", stepOf: "Step {n} of {total}", next: "Next", back: "Back", finish: "Finish",
        s1: "School name", s2: "Number of classes", s3: "First teacher's email", draft: "Draft saved at {time}",
        settingsTitle: "School settings", board: "Board", save: "Save", saved: "Settings saved",
        leaveTitle: "Leave without saving?", stay: "Stay", leave: "Leave", notFound: "Page not found",
        offline: "You are offline. Saved pages still open, but changes cannot be saved." },
      hi: { skip: "मुख्य सामग्री पर जाएँ", home: "होम", setup: "सेटअप", settings: "सेटिंग्स", signOut: "साइन आउट",
        signInTitle: "सेंट मैरीज़ स्कूल में साइन इन करें", email: "स्कूल ईमेल", password: "पासवर्ड", signIn: "साइन इन करें",
        welcome: "फिर से स्वागत है, {name}", fees: "इस सत्र में जमा फ़ीस", due: "फ़ीस की अगली तारीख़",
        "joined.one": "इस हफ़्ते {count} नया छात्र जुड़ा", "joined.other": "इस हफ़्ते {count} नए छात्र जुड़े",
        setupTitle: "अपना स्कूल सेट अप करें", stepOf: "{total} में से चरण {n}", next: "आगे", back: "पीछे", finish: "पूरा करें",
        s1: "स्कूल का नाम", s2: "कक्षाओं की संख्या", s3: "पहले शिक्षक का ईमेल", draft: "ड्राफ़्ट {time} पर सहेजा गया",
        settingsTitle: "स्कूल सेटिंग्स", board: "बोर्ड", save: "सहेजें", saved: "सेटिंग्स सहेज ली गईं",
        leaveTitle: "बिना सहेजे जाना है?", stay: "रुकें", leave: "जाएँ", notFound: "पेज नहीं मिला",
        offline: "आप ऑफ़लाइन हैं। सहेजे गए पेज खुलेंगे, पर बदलाव सहेजे नहीं जा सकते।" }
    };
    const store = {
      get(key) { try { return localStorage.getItem(key); } catch { return null; } },
      set(key, value) { try { localStorage.setItem(key, value); } catch {} },
      remove(key) { try { localStorage.removeItem(key); } catch {} }
    };
    let lang = store.get("demo-vd-lang") === "hi" ? "hi" : "en";
    let session = null;
    let dirty = false;
    let current = "";
    let school = { name: "St Mary's School, Kochi", board: "CBSE" };

    const locale = () => (lang === "hi" ? "hi-IN" : "en-IN");
    const t = (key, vars = {}) => (messages[lang][key] ?? messages.en[key]).replace(/\{(\w+)\}/g, (_, k) => vars[k]);
    const plural = (key, count) => t(`${key}.${new Intl.PluralRules(locale()).select(count)}`, { count });
    const rupees = (n) => new Intl.NumberFormat(locale(), { style: "currency", currency: "INR", maximumFractionDigits: 0 }).format(n);

    function safeReturnTo(value) {                     // from Step 2
      if (!value) return "/app";
      const url = new URL(value, ORIGIN);
      const ok = url.origin === ORIGIN && (url.pathname === "/app" || url.pathname.startsWith("/app/"));
      return ok ? url.pathname + url.search : "/app";
    }

    function h(tag, props = {}, ...children) {
      const el = document.createElement(tag);
      for (const [key, value] of Object.entries(props)) {
        if (key === "text") el.textContent = value;
        else if (key.startsWith("on")) el.addEventListener(key.slice(2), value);
        else el.setAttribute(key, value);
      }
      el.append(...children);
      return el;
    }

    // ---------- Views ----------
    function loginView(params, url) {
      const form = h("form", { onsubmit(event) {
        event.preventDefault();
        session = { name: "Meera" };                   // real app: the server checks the password
        navigate(safeReturnTo(url.searchParams.get("returnTo")), { replace: true });
      } },
        h("label", { for: "email", text: t("email") }),
        h("input", { id: "email", type: "email", autocomplete: "username webauthn", required: "", value: "meera@stmarys.example" }),
        h("label", { for: "password", text: t("password") }),
        h("input", { id: "password", type: "password", autocomplete: "current-password", required: "" }),
        h("p", {}, h("button", { text: t("signIn") })));
      return h("div", {}, h("h1", { tabindex: "-1", text: t("signInTitle") }), form);
    }

    function homeView() {
      const due = new Date("2026-12-10T09:00:00+05:30");
      return h("div", {},
        h("h1", { tabindex: "-1", text: t("welcome", { name: session.name }) }),
        h("dl", {},
          h("dt", { text: t("fees") }), h("dd", { text: rupees(1825000) }),
          h("dt", { text: t("due") }),
          h("dd", { text: new Intl.DateTimeFormat(locale(), { dateStyle: "long", timeZone: "Asia/Kolkata" }).format(due) })),
        h("p", { text: plural("joined", 3) }));
    }

    function wizardView({ step }) {
      const fields = [["s1", "text", "school"], ["s2", "number", "classes"], ["s3", "email", "teacher"]];
      const n = Math.min(Math.max(Number(step) || 1, 1), fields.length);
      const [labelKey, type, name] = fields[n - 1];
      const draft = JSON.parse(store.get("demo-vd-onboarding") ?? "{}");
      const status = h("p", { role: "status" });
      const input = h("input", { id: "field", type, name, value: draft[name] ?? "", oninput(event) {
        draft[name] = event.target.value;
        store.set("demo-vd-onboarding", JSON.stringify(draft));
        status.textContent = t("draft", { time: new Intl.DateTimeFormat(locale(), { timeStyle: "short" }).format(new Date()) });
      } });
      const list = h("ol", {}, ...fields.map(([key], i) =>
        h("li", i === n - 1 ? { "aria-current": "step", text: t(key) } : { text: t(key) })));
      const form = h("form", { onsubmit(event) {
        event.preventDefault();
        if (n < fields.length) return navigate(`/app/onboarding/${n + 1}`);
        store.remove("demo-vd-onboarding");
        navigate("/app");
      } },
        h("label", { for: "field", text: t(labelKey) }), input,
        h("p", {},
          n > 1 ? h("a", { href: `/app/onboarding/${n - 1}`, text: t("back") }) : "", " ",
          h("button", { text: n < fields.length ? t("next") : t("finish") })));
      return h("div", {},
        h("h1", { tabindex: "-1", text: t("setupTitle") }),
        h("p", { id: "step-of", text: t("stepOf", { n, total: fields.length }) }),
        h("progress", { value: n, max: fields.length, "aria-labelledby": "step-of" }),
        list, form, status);
    }

    function settingsView() {
      const status = h("p", { role: "status" });
      const form = h("form", {
        oninput() { dirty = true; },
        onsubmit(event) {
          event.preventDefault();
          school = { name: form.elements.name.value, board: form.elements.board.value };
          dirty = false;
          status.textContent = t("saved");
        } },
        h("label", { for: "name", text: t("s1") }),
        h("input", { id: "name", name: "name", value: school.name, required: "" }),
        h("label", { for: "board", text: t("board") }),
        h("select", { id: "board", name: "board" },
          ...["CBSE", "ICSE", "Kerala State Board"].map((b) => h("option", b === school.board ? { selected: "", text: b } : { text: b }))),
        h("p", {}, h("button", { text: t("save") })));
      return h("div", {}, h("h1", { tabindex: "-1", text: t("settingsTitle") }), form, status);
    }

    function notFoundView() {
      return h("div", {}, h("h1", { tabindex: "-1", text: t("notFound") }), h("p", {}, h("a", { href: "/app", text: t("home") })));
    }

    // ---------- Router ----------
    const routes = [
      { path: "/login", isPublic: true, title: "signInTitle", view: loginView },
      { path: "/app", title: "home", view: homeView },
      { path: "/app/onboarding/:step", title: "setupTitle", view: wizardView },
      { path: "/app/settings", title: "settingsTitle", view: settingsView }
    ];

    function match(pathname) {
      for (const route of routes) {
        const names = [];
        const pattern = new RegExp("^" + route.path.replace(/:(\w+)/g, (_, name) => { names.push(name); return "([^/]+)"; }) + "$");
        const found = pattern.exec(pathname);
        if (found) return { route, params: Object.fromEntries(names.map((name, i) => [name, found[i + 1]])) };
      }
      return { route: { isPublic: true, title: "notFound", view: notFoundView }, params: {} };
    }

    function guard(path) {
      const url = new URL(path, ORIGIN);
      if (match(url.pathname).route.isPublic || session) return path;
      return "/login?returnTo=" + encodeURIComponent(url.pathname + url.search);
    }

    function setUrl(method, path) {
      try { history[method]({ path }, "", path); }
      catch { history[method]({ path }, ""); }          // about:srcdoc in the editor: keep state only
      document.querySelector("#address").textContent = ORIGIN + path;
    }

    function confirmLeave() {
      const dialog = document.querySelector("#leave");
      dialog.returnValue = "";
      dialog.showModal();
      return new Promise((resolve) =>
        dialog.addEventListener("close", () => resolve(dialog.returnValue === "leave"), { once: true }));
    }

    async function navigate(path, { replace = false } = {}) {
      if (path === current) return;
      if (dirty && !(await confirmLeave())) return;
      dirty = false;
      const target = guard(path);
      setUrl(replace || target !== path ? "replaceState" : "pushState", target);
      render(target, true);
    }

    function render(path, moveFocus) {
      current = path;
      const url = new URL(path, ORIGIN);
      const { route, params } = match(url.pathname);
      document.querySelector("#main").replaceChildren(route.view(params, url));
      document.title = `${t(route.title, params)} | VidyaDesk`;
      translateChrome();
      if (moveFocus) document.querySelector("#main h1").focus();
    }

    function translateChrome() {
      document.documentElement.lang = lang;
      for (const el of document.querySelectorAll("[data-i18n]")) el.textContent = t(el.dataset.i18n);
      const here = new URL(current, ORIGIN).pathname;
      for (const link of document.querySelectorAll("nav a")) {
        const section = link.dataset.section;
        const active = section === "/app" ? here === "/app" : here.startsWith(section);
        if (active) link.setAttribute("aria-current", "page"); else link.removeAttribute("aria-current");
      }
      document.querySelector("#nav").hidden = document.querySelector("#signout").hidden = !session;
      const other = document.querySelector("#lang");
      other.lang = lang === "hi" ? "en" : "hi";
      other.textContent = lang === "hi" ? "English" : "हिन्दी";
      updateOnline();
    }

    function updateOnline() {
      const banner = document.querySelector("#offline");
      banner.hidden = navigator.onLine;
      banner.textContent = navigator.onLine ? "" : t("offline");
    }

    // ---------- Events ----------
    document.addEventListener("click", (event) => {
      const link = event.target.closest("a[href^='/']");
      if (!link || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
      event.preventDefault();
      navigate(link.getAttribute("href"));
    });
    window.addEventListener("popstate", (event) => {
      dirty = false;                                   // Back cannot be cancelled; drafts protect wizard work
      const wanted = event.state?.path ?? "/app";
      const target = guard(wanted);
      if (target !== wanted) setUrl("replaceState", target);
      else document.querySelector("#address").textContent = ORIGIN + target;
      render(target, true);
    });
    document.querySelector("#signout").addEventListener("click", () => {
      session = null;                                  // real app: POST /logout, which clears site data
      dirty = false;
      navigate("/login", { replace: true });
    });
    document.querySelector("#lang").addEventListener("click", () => {
      lang = lang === "hi" ? "en" : "hi";
      store.set("demo-vd-lang", lang);
      if (dirty) translateChrome(); else render(current, false);
    });
    addEventListener("online", updateOnline);
    addEventListener("offline", updateOnline);

    // First load: the address decides; the guard may redirect
    const first = guard("/app");
    setUrl("replaceState", first);
    render(first, false);
  </script>
</body>
</html>

The guard redirects /app to /login?returnTo=%2Fapp. Type any password and sign in: focus lands on "Welcome back, Meera". In Set up, type a school name and watch "Draft saved"; go Home and back, and it is still there. Edit Settings, then click Home: the dialog asks first. Press हिन्दी: labels, date and plural sentence change, and the choice survives a reload. Sign out and press the browser's Back button: the guard sends you to sign-in again.

Step 5: English and Hindi done properly

Multilingual HTML Architecture used separate pages per language. In an app, one shell serves both, so the rules move into code:

  • Set lang on <html> on every switch; screen readers change voice and browsers pick Devanagari fonts from it. The switch button carries the language of its own text (lang="hi" on "हिन्दी").
  • Never join sentence pieces with +. Word order differs ("Step 2 of 3" is "3 में से चरण 2"), so each sentence is one message with placeholders.
  • Format numbers, money and dates with Intl; take plural forms from Intl.PluralRules, and give zero its own message.
  • Save the choice in the user's profile on the server too.
JavaScript
const catalogue = {
  "en-IN": {
    "joined.=0": "No new students joined",
    "joined.one": "{count} new student joined",
    "joined.other": "{count} new students joined"
  },
  "hi-IN": {
    "joined.=0": "कोई नया छात्र नहीं जुड़ा",
    "joined.one": "{count} नया छात्र जुड़ा",
    "joined.other": "{count} नए छात्र जुड़े"
  }
};

function plural(locale, key, count) {
  const messages = catalogue[locale];
  const form = new Intl.PluralRules(locale).select(count);          // "one" or "other"
  const text = messages[`${key}.=${count}`] ?? messages[`${key}.${form}`];
  return text.replace("{count}", new Intl.NumberFormat(locale).format(count));
}

const due = new Date("2026-12-10T09:00:00+05:30");
for (const locale of ["en-IN", "hi-IN"]) {
  const money = new Intl.NumberFormat(locale, { style: "currency", currency: "INR", maximumFractionDigits: 0 });
  const date = new Intl.DateTimeFormat(locale, { dateStyle: "long", timeZone: "Asia/Kolkata" });
  const when = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
  console.log(locale, "|", money.format(1825000), "|", date.format(due), "|",
              when.format(-1, "day"), "/", when.format(1, "day"));
  console.log("  ", [0, 1, 3].map((n) => plural(locale, "joined", n)).join(" | "));
  console.log("   PluralRules:", [0, 1, 3].map((n) => new Intl.PluralRules(locale).select(n)).join(", "));
}
console.log(new Intl.NumberFormat("hi-IN-u-nu-deva").format(1825000));
Output
en-IN | ₹18,25,000 | 10 December 2026 | yesterday / tomorrow
   No new students joined | 1 new student joined | 3 new students joined
   PluralRules: other, one, other
hi-IN | ₹18,25,000 | 10 दिसंबर 2026 | कल / कल
   कोई नया छात्र नहीं जुड़ा | 1 नया छात्र जुड़ा | 3 नए छात्र जुड़े
   PluralRules: one, one, other
१८,२५,०००

Three surprises: Hindi puts 0 in the "one" group, which is why the zero message exists. "कल" means both yesterday and tomorrow, so show the full date beside relative dates. And -u-nu-deva switches to Devanagari digits, which some schools prefer on printed notices. (Output from Node 22.14; browsers use the same CLDR data, but exact strings can change between versions, so do not hard-code them in tests.)

Step 6: An offline-capable shell

Teachers in hill schools near Munnar work on weak mobile data. The goal is modest: the shell opens offline and shows the banner from the Try-it. A worker cannot run in the Try-it editor, which has no real address, so here is the plain file:

JavaScript
// /app/sw.js: keeps the VidyaDesk app shell available offline
const VERSION = "shell-2026-11-15";
const SHELL = ["/app/", "/app/app.js", "/app/app.css", "/app/i18n/en.json", "/app/i18n/hi.json"];

self.addEventListener("install", (event) => {
  event.waitUntil(caches.open(VERSION).then((cache) => cache.addAll(SHELL)));
});

self.addEventListener("activate", (event) => {
  event.waitUntil((async () => {
    for (const key of await caches.keys()) {
      if (key !== VERSION) await caches.delete(key);       // old shells go
    }
    await self.clients.claim();
  })());
});

self.addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);
  if (url.origin !== location.origin || event.request.method !== "GET") return;
  if (url.pathname.startsWith("/api/")) return;              // school data: network only

  if (event.request.mode === "navigate" && url.pathname.startsWith("/app")) {
    // Every /app/... address is the same shell; the router draws the view.
    event.respondWith(fetch(event.request).catch(() => caches.match("/app/")));
    return;
  }
  event.respondWith(caches.match(event.request).then((hit) => hit ?? fetch(event.request)));
});

The key line is /api/. The shell is the same for every school, so caching it is safe; student records belong to one tenant and one user, so they never enter Cache Storage. Sign-out is a POST /logout whose response carries Clear-Site-Data: "cache", "storage". That clears the browser cache, local storage, IndexedDB and service worker registrations for the origin, so the next person on a shared staff-room computer sees nothing. Lifecycle details are in Service Workers Fundamentals.

Step 7: Strict CSP and Trusted Types

The shell is a static file served from a CDN, so a fresh nonce per request is not available. It has no inline scripts, so the app origin can use this header:

Text
Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:;
  font-src 'self'; connect-src 'self'; manifest-src 'self'; worker-src 'self'; form-action 'self';
  frame-ancestors 'none'; base-uri 'none'; require-trusted-types-for 'script'; trusted-types vd-static;
  report-to csp
Strict-Transport-Security: max-age=63072000; includeSubDomains
X-Content-Type-Options: nosniff
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
Cross-Origin-Opener-Policy: same-origin

(The CSP is one line in a real header.) script-src 'self' is safe only because the app origin serves nothing users control: uploaded report cards and photos live on a separate origin, such as files.vidyadesk-usercontent.example, and there are no JSONP endpoints. If you need an inline loader, use a hash with 'strict-dynamic' from Content Security Policy Advanced.

The design system was built for this header. In a headless Chrome test under style-src 'self', adopted stylesheets and element.style.setProperty() applied, while a style attribute set from script was blocked. Shadow markup uses the vd-static policy and views use textContent, so trusted-types lists one name. Roll the header out as Content-Security-Policy-Report-Only first and read a week of reports.

Step 8: A performance budget

A performance budget is a set of limits agreed before building, like a household's monthly budget. A pull request that breaks one fails CI. These numbers are VidyaDesk's choices; Core Web Vitals call LCP 2.5 s, INP 200 ms and CLS 0.1 "good" at the 75th percentile of real visits.

BudgetMarketing pagesApp shell
Largest Contentful Paint2.0 s2.5 s
Interaction to Next Paint200 ms200 ms
Cumulative Layout Shift0.050.1
JavaScript transferred on first load30 KB150 KB
Web fonts2 files2 files (Latin and a Devanagari subset)

A Lighthouse page-load audit has no real user, so it cannot measure INP; Total Blocking Time is its proxy, and INP comes from field data. Views load with dynamic import(), so Settings code downloads only when someone opens Settings. Lighthouse CI checks the lab budget:

JSON
{
  "ci": {
    "collect": { "staticDistDir": "./dist", "numberOfRuns": 3 },
    "assert": {
      "assertions": {
        "categories:performance": ["error", { "minScore": 0.9 }],
        "categories:accessibility": ["error", { "minScore": 1 }],
        "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
        "cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }],
        "total-blocking-time": ["warn", { "maxNumericValue": 200 }],
        "resource-summary:script:size": ["error", { "maxNumericValue": 153600 }]
      }
    }
  }
}

Sizes in these assertions are in bytes, so 150 KB is 153600. More on reading the report is in Lighthouse Performance Auditing.

Step 9: The CI pipeline

CI (continuous integration) runs every check on every pull request, so nobody merges a broken build. CI/CD for Frontend Projects builds one in detail; this is VidyaDesk's summary:

StageToolFails when
Linthtml-validate, Stylelint, ESLintInvalid HTML, banned patterns such as innerHTML =
Unit testsNode test runnerRouter matching, safeReturnTo, plural messages break
Browser testsPlaywright with axeA journey fails, focus is lost, an accessibility rule fails
BudgetsLighthouse CIAny assertion in lighthouserc.json fails
HeadersA small script with fetchCSP, HSTS or noindex on /app/ is missing
PreviewHosting providerBuild fails; otherwise a preview link is posted on the pull request

A browser test guards the focus rule from Step 4, which screen reader users notice first:

JavaScript
import { test, expect } from "@playwright/test";

test("moving between views focuses the new heading", async ({ page }) => {
  await page.goto("/login?returnTo=/app/settings");
  await page.getByLabel("Password").fill("correct horse battery staple");
  await page.getByRole("button", { name: "Sign in" }).click();
  await expect(page.getByRole("heading", { level: 1 })).toBeFocused();
  await expect(page).toHaveTitle(/School settings/);
  await page.getByRole("link", { name: "Home" }).click();
  await expect(page.getByRole("heading", { name: /Welcome back/ })).toBeFocused();
});

Run it with npx playwright test; Playwright Browser Testing explains the setup.

Common mistakes

  • Sign-in inside the single-page app. It breaks without JavaScript and confuses password managers.
  • Trusting the front end for tenant isolation. Hiding a menu item is not security.
  • Tokens in localStorage. Use an HttpOnly __Host- cookie instead.
  • Silent route changes. Without a title change and focus move, screen reader users are lost.
  • Caching API responses in the service worker. One school's data can reach the next user of a shared computer.
  • Concatenated translations. Word order and plural rules differ between languages.

Interview questions

1. Why keep the marketing site and the app as separate front ends?

They have opposite needs. The marketing site must be indexable, fast for first visits and cacheable on a CDN; the app is private, used for hours, and needs a router and state. Separating them keeps both simple.

2. What must a client-side router do after it changes the view?

Update document.title, focus the new main heading (with tabindex="-1") and update aria-current in the navigation. It must also handle popstate and show a real "not found" view for unknown paths.

3. How do you stop an open redirect after login?

Parse the returnTo value with new URL() against your own origin, then accept it only if the origin matches and the path is inside the app. Simple string checks miss tricks like //evil.example and /\evil.example. The server must repeat the check, because it performs the redirect.

4. How do web components fit with a strict CSP and Trusted Types?

Use constructable stylesheets through adoptedStyleSheets instead of inline styles. Create shadow markup through a Trusted Types policy that returns only fixed templates, and set text with textContent. The CSP then needs no 'unsafe-inline'.

5. What should a SaaS service worker never cache?

Personal or tenant data from the API, because everyone using that browser profile shares Cache Storage. Cache only the shell, which is identical for all users, and send Clear-Site-Data on sign-out.

Key points

  • A SaaS product is two front ends: a public, indexable marketing site and a private app shell.
  • Sign-in stays as server-rendered forms; sessions live in __Host- cookies; return addresses are validated.
  • Design-system components use tokens, parts, adopted stylesheets and one Trusted Types policy.
  • The router guards routes, protects unsaved work, and moves focus and updates the title on every view change.
  • Translations are whole messages with Intl formatting and plural rules; Hindi treats 0 as "one".
  • The service worker caches only the shell; budgets and CI enforce speed, security and accessibility on every pull request.

Exercise

Extend the app shell Try-it with a route /app/attendance/:class (for example /app/attendance/7B). Show a heading "Attendance: Class 7B", three students with a present checkbox each, and a Save button. Add a nav link. Mark the form dirty on change, so the leave dialog protects unsaved attendance. Translate every new string into Hindi, including a plural "{count} students absent" message. /app/attendance/ must show the not-found view.

Show solution

Add messages, a view and one route. The view reads params.class, so the pattern does all the parsing:

JavaScript
Object.assign(messages.en, { attendanceNav: "Attendance", attendance: "Attendance: Class {class}",
  "absent.one": "{count} student absent", "absent.other": "{count} students absent" });
Object.assign(messages.hi, { attendanceNav: "हाज़िरी", attendance: "हाज़िरी: कक्षा {class}",
  "absent.one": "{count} छात्र अनुपस्थित", "absent.other": "{count} छात्र अनुपस्थित" });

function attendanceView(params) {
  const summary = h("p", { role: "status" });
  const students = ["Aarav", "Priya", "Kabir"];
  const form = h("form", {
    onchange() {
      dirty = true;
      const absent = [...form.querySelectorAll("input")].filter((box) => !box.checked).length;
      summary.textContent = plural("absent", absent);
    },
    onsubmit(event) { event.preventDefault(); dirty = false; summary.textContent = t("saved"); } },
    ...students.map((name) => h("label", {}, h("input", { type: "checkbox", checked: "" }), " " + name)),
    h("p", {}, h("button", { text: t("save") })));
  return h("div", {}, h("h1", { tabindex: "-1", text: t("attendance", params) }), form, summary);
}

routes.push({ path: "/app/attendance/:class", title: "attendance", view: attendanceView });

Put this code after the routes array and add <a href="/app/attendance/7B" data-i18n="attendanceNav" data-section="/app/attendance"></a> to the nav. render() passes route parameters to t(), so the tab title becomes "Attendance: Class 7B". The pattern ([^/]+) needs at least one character, so /app/attendance/ shows the not-found view. Untick Priya and click Home: the leave dialog appears.

Quick Quiz

1. Why does VidyaDesk name its session cookie __Host-session?

2. After a client-side route change, where should focus go?

3. What does new Intl.PluralRules("hi-IN").select(0) return?

4. Which response header removes caches, storage and service workers when a user signs out?

Learn HTML with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call