<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Web Development - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Web Development - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 26 Nov 2026 00:34:31 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/web-development/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Set Up and Customize Light and Dark Mode in shadcn with Next.js ]]>
                </title>
                <description>
                    <![CDATA[ If you've created a Next.js project with shadcn/ui recently, there's a good chance dark mode is already set up. I noticed this while looking through a fresh project. I opened app/globals.css expecting ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-set-up-and-customize-light-and-dark-mode-in-shadcn-with-next-js/</link>
                <guid isPermaLink="false">6b06284b7f6906157677974a</guid>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ shadcn ]]>
                    </category>
                
                    <category>
                        <![CDATA[ dark mode ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ajay Patel ]]>
                </dc:creator>
                <pubDate>Wed, 25 Nov 2026 00:14:03 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/cec83f18-c647-46a4-a7ca-125aea525bed.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>If you've created a Next.js project with shadcn/ui recently, there's a good chance dark mode is already set up.</p>
<p>I noticed this while looking through a fresh project. I opened <code>app/globals.css</code> expecting to add the theme colors, but the light and dark values were already there. Then I checked the <code>components</code> folder and found a <code>theme-provider.tsx</code> file that had already been created for me.</p>
<p>That raised a more useful question: if shadcn has already done most of the setup, what do you actually need to build?</p>
<p>In this guide, we'll look at the dark-mode setup that comes with a generated shadcn project, understand how the pieces work together, and build a theme switcher that users can control. We'll also look at how to customize the colors without adding light and dark classes to every component.</p>
<p>By the end, you'll know:</p>
<ul>
<li>Where shadcn stores its light and dark theme values</li>
<li>How CSS variables and Tailwind theme variables work together</li>
<li>What <code>next-themes</code> does in a Next.js project</li>
<li>How to add a two-state or three-option theme switcher</li>
<li>How to add your own theme tokens</li>
</ul>
<p>We'll start with the generated project and work through the theme setup before building the switcher.</p>
<p><strong>Before you start:</strong> This guide follows the Next.js project generated by <a href="https://ui.shadcn.com/create">shadcn/create</a>. Your project may look a little different if you use another framework, an older shadcn setup, or a different component style. I'll point out the parts you should check in your own project.</p>
<p>The examples and screenshots in this article are based on the companion project. Once you have the project locally, you can run <code>pnpm install</code> and <code>pnpm dev</code> to try it yourself.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/b000ee75-6dbb-480e-81cd-d7f39a07533c.png" alt="The companion demo app in light mode." style="display: block;" width="600" height="400" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/c99c2fb2-3a3b-48db-9846-59bf4be10834.png" alt="The companion demo app in dark mode." style="display: block;" width="600" height="400" loading="lazy">

<p><em>The same page is shown in both themes. Only the active theme values change.</em></p>
<p>The page uses the same JSX in both screenshots. The theme changes the values behind the CSS variables, and the browser updates the styles.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a href="#heading-project-setup-and-versions">Project Setup and Versions</a></li>
<li><a href="#heading-1-create-a-shadcn-project">1. Create a shadcn Project</a></li>
<li><a href="#heading-2-what-shadcn-has-already-configured">2. What shadcn Has Already Configured</a></li>
<li><a href="#heading-3-where-the-theme-colors-live">3. Where the Theme Colors Live</a><ul>
<li><a href="#heading-why-semantic-tokens-are-useful">Why Semantic Tokens Are Useful</a></li>
<li><a href="#heading-understanding-the-foreground-pairs">Understanding the Foreground Pairs</a></li>
</ul>
</li>
<li><a href="#heading-4-how-tailwind-gets-its-theme-classes">4. How Tailwind Gets its Theme Classes</a><ul>
<li><a href="#heading-what-the-dark-variant-does">What the dark: Variant Does</a></li>
</ul>
</li>
<li><a href="#heading-5-what-next-themes-does">5. What next-themes Does</a></li>
<li><a href="#heading-6-the-theme-provider-thats-already-in-your-project">6. The Theme Provider That's Already in Your Project</a><ul>
<li><a href="#heading-theres-a-keyboard-shortcut-too">There's a Keyboard Shortcut Too</a></li>
<li><a href="#heading-what-the-provider-options-mean">What the Provider Options Mean</a></li>
<li><a href="#heading-why-layouttsx-uses-suppresshydrationwarning">Why layout.tsx Uses suppressHydrationWarning</a></li>
</ul>
</li>
<li><a href="#heading-7-build-a-theme-switcher">7. Build a Theme Switcher</a><ul>
<li><a href="#heading-option-1-a-light-and-dark-toggle">Option 1: A light and Dark Toggle</a></li>
<li><a href="#heading-option-2-a-light-dark-and-system-menu">Option 2: A Light, Dark, and System Menu</a></li>
</ul>
</li>
<li><a href="#heading-8-why-the-icon-animation-may-not-work">8. Why the Icon Animation May Not Work</a></li>
<li><a href="#heading-9-customize-your-theme">9. Customize Your Theme</a><ul>
<li><a href="#heading-change-an-existing-token">Change an Existing Token</a></li>
<li><a href="#heading-add-a-custom-token">Add a Custom Token</a></li>
<li><a href="#heading-when-should-you-use-dark">When Should You Usedark:</a></li>
</ul>
</li>
<li><a href="#heading-conclusion">Conclusion</a></li>
<li><a href="#heading-references">References</a></li>
</ul>
<h2 id="heading-project-setup-and-versions">Project Setup and Versions</h2>
<p>The versions below are the versions used in the companion project, which was generated in August 2026. Shadcn's generated output changes over time, so check your own <code>package.json</code> if you're following along with a newer project.</p>
<table>
<thead>
<tr>
<th>Package</th>
<th>Version</th>
</tr>
</thead>
<tbody><tr>
<td><code>next</code></td>
<td><code>16.2.6</code></td>
</tr>
<tr>
<td><code>react</code></td>
<td><code>19.2.4</code></td>
</tr>
<tr>
<td><code>next-themes</code></td>
<td><code>0.4.6</code></td>
</tr>
<tr>
<td><code>@base-ui/react</code></td>
<td><code>1.7.0</code></td>
</tr>
<tr>
<td><code>tailwindcss</code></td>
<td><code>4</code></td>
</tr>
</tbody></table>
<p>The project's <code>components.json</code> includes <code>"style": "base-nova"</code> and <code>"baseColor": "stone"</code>. The <code>base-nova</code> style uses Base UI primitives. This matters when we build the dropdown switcher later, because the Base UI version uses the <code>render</code> prop where many older Radix-based examples use <code>asChild</code>.</p>
<h2 id="heading-1-create-a-shadcn-project">1. Create a shadcn Project</h2>
<p>You don't need to configure Next.js and Tailwind from scratch for this guide. Shadcn's project builder can generate a starter project with the theme setup included.</p>
<p>Open <a href="https://ui.shadcn.com/create">shadcn/create</a> and select <strong>Get Started</strong>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/c16207c2-7609-40bc-8f4d-fbfc8c15685d.png" alt="The shadcn/create page with the Get Started dialog open." style="display: block;" width="600" height="400" loading="lazy">

<p>Choose the style, base color, chart color, fonts, icon library, and radius from the controls. These choices affect the theme values that will be added to your project. We'll look at those values in the next section.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/9f78e27d-41a8-4885-9cea-8f272f178229.png" alt="The shadcn theme builder with controls for style, colors, fonts, icons, and radius." style="display: block;" width="600" height="400" loading="lazy">

<p>When you're happy with the setup, select <strong>Get Code</strong>, choose <strong>Next.js</strong>, and copy the command.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/46c4b750-21f1-4da9-9416-dc0b3ba7707a.png" alt="The Get Code dialog with Next.js selected and the generated setup command visible." style="display: block;" width="600" height="400" loading="lazy">

<p>Run the command in your terminal. The preset ID in your command may be different from the example below:</p>
<pre><code class="language-bash">pnpm dlx shadcn@latest init --preset b0 --template next
</code></pre>
<p>If you're building a complete product, you may prefer to start with a ready-made <a href="https://shadcnstudio.com/templates">shadcn template</a> and adapt it to your app. The same theme setup covered in this guide can be used in a template-based project.</p>
<p>The generated project has a structure similar to this:</p>
<pre><code class="language-plaintext">shadcn-light-dark-theme/
├── app/
│   ├── globals.css          # every theme token, light and dark
│   ├── layout.tsx           # fonts and ThemeProvider already wired
│   └── page.tsx
├── components/
│   ├── theme-provider.tsx   # next-themes, already configured
│   └── ui/button.tsx
├── lib/utils.ts
└── components.json
</code></pre>
<p>Start the development server:</p>
<pre><code class="language-bash">pnpm dev
</code></pre>
<p>Open <code>http://localhost:3000</code>. The companion project also includes a keyboard shortcut: pressing <code>d</code> switches between light and dark mode.</p>
<p>The important point is that the theme setup is already present. Before adding anything, let's see what the generator has configured.</p>
<h2 id="heading-2-what-shadcn-has-already-configured">2. What shadcn Has Already Configured</h2>
<p>A generated project includes most of the pieces you need for light and dark themes. Here's where to find them:</p>
<table>
<thead>
<tr>
<th>Part</th>
<th>Where to find it</th>
<th>Included</th>
</tr>
</thead>
<tbody><tr>
<td>Light theme values</td>
<td><code>app/globals.css</code> then <code>:root</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Dark theme values</td>
<td><code>app/globals.css</code> then <code>.dark</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Tailwind's <code>dark:</code> variant</td>
<td><code>app/globals.css</code> then <code>@custom-variant</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Tailwind utilities for theme tokens</td>
<td><code>app/globals.css</code> then <code>@theme inline</code></td>
<td>Yes</td>
</tr>
<tr>
<td><code>next-themes</code> package</td>
<td><code>package.json</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Theme provider</td>
<td><code>components/theme-provider.tsx</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Provider added to the app</td>
<td><code>app/layout.tsx</code></td>
<td>Yes</td>
</tr>
<tr>
<td>Hydration warning handling</td>
<td><code>app/layout.tsx</code></td>
<td>Yes</td>
</tr>
<tr>
<td>A visible theme switcher</td>
<td>Your UI</td>
<td><strong>You add this</strong></td>
</tr>
</tbody></table>
<p>So the main piece you'll usually need to add is the control that lets someone choose a theme. The rest is already configured, although it's worth understanding before you start customizing it.</p>
<h2 id="heading-3-where-the-theme-colors-live">3. Where the Theme Colors Live</h2>
<p>Open <code>app/globals.css</code>. You'll find two groups of CSS variables: one inside <code>:root</code> and another inside <code>.dark</code>.</p>
<p>Here's a shortened example based on the generated project:</p>
<pre><code class="language-css">:root {
  --background: oklch(1 0 0);
  --foreground: oklch(0.147 0.004 49.25);
  --card: oklch(1 0 0);
  --card-foreground: oklch(0.147 0.004 49.25);
  --primary: oklch(0.555 0.163 48.998);
  --primary-foreground: oklch(0.987 0.022 95.277);
  --muted: oklch(0.97 0.001 106.424);
  --muted-foreground: oklch(0.553 0.013 58.071);
  --border: oklch(0.923 0.003 48.717);
  --radius: 0.625rem;
  /* …about thirty in total */
}

.dark {
  --background: oklch(0.147 0.004 49.25);
  --foreground: oklch(0.985 0.001 106.423);
  --card: oklch(0.216 0.006 56.043);
  --card-foreground: oklch(0.985 0.001 106.423);
  --primary: oklch(0.473 0.137 46.201);
  --primary-foreground: oklch(0.987 0.022 95.277);
  --muted: oklch(0.268 0.007 34.298);
  --muted-foreground: oklch(0.709 0.01 56.259);
  --border: oklch(1 0 0 / 10%);
}
</code></pre>
<p>The idea is straightforward:</p>
<pre><code class="language-plaintext">:root   →  light theme values
.dark   →  dark theme values
</code></pre>
<p>Both blocks use the same variable names. The values change depending on whether the <code>dark</code> class is present on the page.</p>
<p>For example, <code>--background</code> is white in the light theme and near-black in the dark theme. <code>--foreground</code> changes in the opposite direction so the text remains visible against the background.</p>
<p>You'll also see variables such as <code>--radius</code>. It isn't a color, but it's part of the theme configuration. In this setup, the radius is defined once because the corner shape doesn't need a separate value for dark mode.</p>
<h3 id="heading-why-semantic-tokens-are-useful">Why Semantic Tokens Are Useful</h3>
<p>Theme variables are especially useful when you're building components. Compare these two examples.</p>
<p>Without semantic tokens, you might add separate light and dark colors directly to the component:</p>
<pre><code class="language-tsx">&lt;div className="bg-white text-black dark:bg-black dark:text-white"&gt;
  Hello
&lt;/div&gt;
</code></pre>
<p>That works, but you have to repeat the same decisions throughout your app. If your color palette changes, you'll need to find and update all those classes.</p>
<p>With semantic tokens, the component can use the theme variable instead:</p>
<pre><code class="language-tsx">&lt;div className="bg-background text-foreground"&gt;
  Hello
&lt;/div&gt;
</code></pre>
<p>The component doesn't need to know whether the page is in light or dark mode. It uses <code>background</code> and <code>foreground</code>, and the active theme supplies the right values.</p>
<p>This is also why shadcn components such as <code>Card</code> can adapt without needing dark-mode classes of their own:</p>
<pre><code class="language-tsx">&lt;Card&gt;
  &lt;CardHeader&gt;
    &lt;CardTitle&gt;Hello&lt;/CardTitle&gt;
  &lt;/CardHeader&gt;
&lt;/Card&gt;
</code></pre>
<p>If you open <code>components/ui/card.tsx</code>, you'll see classes such as <code>bg-card</code> and <code>text-card-foreground</code>. The component uses the semantic tokens, while the theme defines what those tokens look like.</p>
<p>The same idea applies when you add more UI to the project. If you need examples of individual elements built for the shadcn ecosystem, you can refer to <a href="https://shadcnstudio.com/components">Shadcn Components</a> and adapt the ones that fit your interface. Keep the semantic tokens in place so those components follow your light and dark themes.</p>
<h3 id="heading-understanding-the-foreground-pairs">Understanding the Foreground Pairs</h3>
<p>Many theme tokens come in pairs. The first token describes a surface, and the <code>-foreground</code> token describes the text or content that appears on top of it.</p>
<table>
<thead>
<tr>
<th>Surface token</th>
<th>Foreground token</th>
</tr>
</thead>
<tbody><tr>
<td><code>--background</code></td>
<td><code>--foreground</code></td>
</tr>
<tr>
<td><code>--card</code></td>
<td><code>--card-foreground</code></td>
</tr>
<tr>
<td><code>--primary</code></td>
<td><code>--primary-foreground</code></td>
</tr>
<tr>
<td><code>--muted</code></td>
<td><code>--muted-foreground</code></td>
</tr>
</tbody></table>
<p>For example, <code>bg-primary text-primary-foreground</code> uses a matching background and text color. The theme defines both values together so the combination works across its light and dark palettes.</p>
<p>Some tokens, such as <code>--border</code>, <code>--input</code>, and <code>--ring</code>, don't need a foreground pair because they're used for borders, input outlines, and focus indicators.</p>
<p>The companion project displays the token pairs as simple tiles. Each tile uses the same <code>bg-&lt;name&gt; text-&lt;name&gt;-foreground</code> pattern.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/1797b932-d44d-41b2-832d-7855bdc34295.png" alt="Theme token pairs displayed in light mode." style="display: block;" width="600" height="400" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/53a19e7f-cea3-44e9-ac59-67c801297f63.png" alt="The same theme token pairs displayed in dark mode." style="display: block;" width="600" height="400" loading="lazy">

<p>The markup stays the same in both screenshots. Only the active CSS variable values change. The demo also includes a custom <code>--warning</code> token to show how you can extend the theme.</p>
<h2 id="heading-4-how-tailwind-gets-its-theme-classes">4. How Tailwind Gets its Theme Classes</h2>
<p>There's one more part of <code>globals.css</code> that's easy to overlook: the <code>@theme inline</code> block.</p>
<p>A CSS variable such as <code>--primary</code> is available to CSS, but defining it doesn't automatically create Tailwind classes such as <code>bg-primary</code> or <code>text-primary</code>. Tailwind needs to know which variables should become utility classes.</p>
<p>That's what this block does:</p>
<pre><code class="language-css">@theme inline {
  --color-background: var(--background);
  --color-foreground: var(--foreground);
  --color-primary: var(--primary);
  --color-primary-foreground: var(--primary-foreground);
  --color-muted: var(--muted);
  /* …one line per token */
  --radius-sm: calc(var(--radius) * 0.6);
  --radius-md: calc(var(--radius) * 0.8);
  --radius-lg: var(--radius);
  --radius-xl: calc(var(--radius) * 1.4);
}
</code></pre>
<p>For example, this line:</p>
<pre><code class="language-css">--color-primary: var(--primary);
</code></pre>
<p>connects the CSS variable <code>--primary</code> to Tailwind's color utilities. It allows you to use classes such as <code>bg-primary</code>, <code>text-primary</code>, and <code>border-primary</code>.</p>
<p>This is an important step when you add your own tokens. If you define <code>--brand</code> in <code>:root</code> but don't add a matching <code>--color-brand</code> entry in <code>@theme inline</code>, Tailwind won't generate the <code>bg-brand</code> utility for you. The CSS variable can exist and still not be available as a Tailwind utility.</p>
<p>The <code>inline</code> keyword is also important here. It allows the generated utilities to reference the underlying CSS variable, so they use the current value when the theme changes.</p>
<h3 id="heading-what-the-dark-variant-does">What the <code>dark:</code> Variant Does</h3>
<p>You'll also find this line in <code>globals.css</code>:</p>
<pre><code class="language-css">@custom-variant dark (&amp;:is(.dark *));
</code></pre>
<p>This defines how Tailwind's <code>dark:</code> variant works in this setup. A class such as <code>dark:hidden</code> applies when the element is inside an ancestor with the <code>dark</code> class.</p>
<p>There are two details to remember:</p>
<ul>
<li>The theme is represented by a <code>dark</code> class, rather than a <code>data-theme</code> attribute.</li>
<li>The selector targets descendants of the element with the <code>dark</code> class.</li>
</ul>
<p>In this project, <code>next-themes</code> adds the class to the <code>&lt;html&gt;</code> element. That means the elements inside the page can use <code>dark:</code> utilities as expected.</p>
<p>Here's the relationship between the theme class, CSS variables, and Tailwind utilities:</p>
<pre><code class="language-plaintext">.dark on &lt;html&gt;
   ↓
--primary changes value          (globals.css)
   ↓
--color-primary reads it         (@theme inline)
   ↓
bg-primary compiles to var(--primary)
   ↓
every element using bg-primary repaints
</code></pre>
<p>When the theme changes, the browser updates the CSS variables and recalculates the styles that use them. Your components don't need to re-render just because a theme color changed.</p>
<p>So far, we've looked at the CSS side. The next question is what adds or removes the <code>dark</code> class.</p>
<h2 id="heading-5-what-next-themes-does">5. What <code>next-themes</code> Does</h2>
<p>CSS defines what the light and dark themes look like. It doesn't remember a visitor's choice or decide which theme should be active. That's handled by JavaScript.</p>
<p>The generated Next.js project uses <a href="https://github.com/pacocoursey/next-themes"><code>next-themes</code></a> for this.</p>
<p>The library handles a few things for you:</p>
<ul>
<li>Adds or removes the <code>dark</code> class on the <code>&lt;html&gt;</code> element.</li>
<li>Saves the selected theme in <code>localStorage</code>.</li>
<li>Supports a <code>system</code> option that follows the visitor's operating system preference.</li>
<li>Runs a small script before the page is displayed so the saved theme can be applied early.</li>
</ul>
<p>That last point helps prevent a flash of the wrong theme when the page loads. If you wait until a React <code>useEffect</code> runs to apply the theme, the browser may display the page before the effect runs. A visitor who prefers dark mode could briefly see the light version first.</p>
<p>The generated project already includes a theme provider and mounts it in the app layout. Let's take a look at what it does.</p>
<h2 id="heading-6-the-theme-provider-thats-already-in-your-project">6. The Theme Provider That's Already in Your Project</h2>
<p>The generated <code>components/theme-provider.tsx</code> file wraps <code>next-themes</code> and sets a few defaults. Here's the provider from the companion project:</p>
<pre><code class="language-tsx">"use client"

import * as React from "react"
import { ThemeProvider as NextThemesProvider, useTheme } from "next-themes"

function ThemeProvider({
  children,
  ...props
}: React.ComponentProps&lt;typeof NextThemesProvider&gt;) {
  return (
    &lt;NextThemesProvider
      attribute="class"
      defaultTheme="system"
      enableSystem
      disableTransitionOnChange
      {...props}
    &gt;
      &lt;ThemeHotkey /&gt;
      {children}
    &lt;/NextThemesProvider&gt;
  )
}
</code></pre>
<p>The wrapper means you don't need to repeat the same configuration every time you use the provider. In <code>app/layout.tsx</code>, it can be mounted like this:</p>
<pre><code class="language-tsx">&lt;ThemeProvider&gt;{children}&lt;/ThemeProvider&gt;
</code></pre>
<p>The <code>{...props}</code> spread comes after the default props. That means a value passed to <code>ThemeProvider</code> can override the wrapper's defaults.</p>
<h3 id="heading-theres-a-keyboard-shortcut-too">There's a Keyboard Shortcut Too</h3>
<p>The provider file also includes a <code>ThemeHotkey</code> component:</p>
<pre><code class="language-tsx">function isTypingTarget(target: EventTarget | null) {
  if (!(target instanceof HTMLElement)) {
    return false
  }

  return (
    target.isContentEditable ||
    target.tagName === "INPUT" ||
    target.tagName === "TEXTAREA" ||
    target.tagName === "SELECT"
  )
}

function ThemeHotkey() {
  const { resolvedTheme, setTheme } = useTheme()

  React.useEffect(() =&gt; {
    function onKeyDown(event: KeyboardEvent) {
      if (event.defaultPrevented || event.repeat) return
      if (event.metaKey || event.ctrlKey || event.altKey) return
      if (event.key.toLowerCase() !== "d") return
      if (isTypingTarget(event.target)) return

      setTheme(resolvedTheme === "dark" ? "light" : "dark")
    }

    window.addEventListener("keydown", onKeyDown)
    return () =&gt; window.removeEventListener("keydown", onKeyDown)
  }, [resolvedTheme, setTheme])

  return null
}
</code></pre>
<p>This component doesn't render anything on the page. It listens for the <code>d</code> key and switches between light and dark mode.</p>
<p>Notice the checks inside the keyboard handler. They prevent the shortcut from firing when the user is typing in an input, textarea, select, or editable element. The modifier-key check also prevents the shortcut from interfering with combinations such as <code>Cmd+D</code> or <code>Ctrl+D</code>.</p>
<p>If you don't want this shortcut in your project, remove <code>&lt;ThemeHotkey /&gt;</code> from the provider. If you keep it, consider mentioning it somewhere in your app so users know it's available.</p>
<h3 id="heading-what-the-provider-options-mean">What the Provider Options Mean</h3>
<table>
<thead>
<tr>
<th>Option</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><code>attribute="class"</code></td>
<td>Adds a class to <code>&lt;html&gt;</code> instead of a <code>data-theme</code> attribute.</td>
</tr>
<tr>
<td><code>defaultTheme="system"</code></td>
<td>Uses the operating system preference for a first-time visitor.</td>
</tr>
<tr>
<td><code>enableSystem</code></td>
<td>Enables the <code>system</code> theme option.</td>
</tr>
<tr>
<td><code>disableTransitionOnChange</code></td>
<td>Temporarily disables CSS transitions while the theme changes.</td>
</tr>
</tbody></table>
<p>The <code>attribute="class"</code> setting needs to match the CSS setup from the earlier section. The generated stylesheet looks for <code>.dark</code>, so <code>next-themes</code> needs to add a class. If you change the attribute to <code>data-theme</code>, the <code>.dark</code> selector won't match unless you also update your CSS.</p>
<p>If your switcher uses animated icons, this setting can affect their transitions. The behavior is worth considering when you decide how theme changes should look across the page.</p>
<h3 id="heading-why-layouttsx-uses-suppresshydrationwarning">Why <code>layout.tsx</code> Uses <code>suppressHydrationWarning</code></h3>
<p>You may also notice this on the <code>&lt;html&gt;</code> element in <code>app/layout.tsx</code>:</p>
<pre><code class="language-tsx">&lt;html lang="en" suppressHydrationWarning className={cn("antialiased", …)}&gt;
</code></pre>
<p>The theme script can update the <code>&lt;html&gt;</code> class before React hydrates the page. That means the HTML rendered on the server may have a different class from the HTML React sees in the browser.</p>
<p><code>suppressHydrationWarning</code> tells React to suppress that expected warning on this element. It's included in the generated setup for this reason. It applies to that element, rather than disabling hydration warnings throughout the app.</p>
<h2 id="heading-7-build-a-theme-switcher">7. Build a Theme Switcher</h2>
<p>At this point, the theme colors are configured and <code>next-themes</code> can apply the selected theme. What the project still needs is a visible control that lets users change it.</p>
<p>There are two common approaches. You can give users a button that switches between light and dark, or offer a menu with Light, Dark, and System options.</p>
<h3 id="heading-option-1-a-light-and-dark-toggle">Option 1: A light and Dark Toggle</h3>
<p>If your app only needs two modes, a single button is enough:</p>
<pre><code class="language-tsx">"use client"

import { Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"

import { Button } from "@/components/ui/button"

function ModeSwitch() {
  const { resolvedTheme, setTheme } = useTheme()

  return (
    &lt;Button
      variant="ghost"
      size="icon"
      aria-label="Toggle theme"
      onClick={() =&gt; setTheme(resolvedTheme === "dark" ? "light" : "dark")}
    &gt;
      &lt;Sun className="dark:hidden" /&gt;
      &lt;Moon className="hidden dark:block" /&gt;
    &lt;/Button&gt;
  )
}

export { ModeSwitch }
</code></pre>
<p>A few details in this component are worth understanding.</p>
<p>First, use <code>resolvedTheme</code> for a two-state toggle. The <code>theme</code> value can be <code>"system"</code>, while <code>resolvedTheme</code> tells you which theme is currently active: <code>"light"</code> or <code>"dark"</code>. Since this button switches between two visible states, <code>resolvedTheme</code> is the value you want to check.</p>
<p>Second, keep both icons in the DOM. The <code>Sun</code> and <code>Moon</code> icons are shown or hidden with CSS classes. This avoids choosing an icon based on a theme value that may not be available during server rendering.</p>
<p>For comparison, this conditional approach can cause a mismatch between the server-rendered markup and the browser's first render:</p>
<pre><code class="language-tsx">{resolvedTheme === "dark" ? &lt;Moon /&gt; : &lt;Sun /&gt;}
</code></pre>
<p>Finally, add an accessible label. Since the button only contains an icon, <code>aria-label</code> gives screen reader users a useful description of what the button does.</p>
<h3 id="heading-option-2-a-light-dark-and-system-menu">Option 2: A Light, Dark, and System Menu</h3>
<p>If you want users to choose their preferred mode, including the operating system setting, use a dropdown menu.</p>
<p>First, add the dropdown menu component if it's not already in your project:</p>
<pre><code class="language-bash">pnpm dlx shadcn@latest add dropdown-menu
</code></pre>
<p>Then create the switcher:</p>
<pre><code class="language-tsx">"use client"

import { ChevronDown, Monitor, Moon, Sun } from "lucide-react"
import { useTheme } from "next-themes"

import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"

const MODES = [
  { value: "light", label: "Light", icon: Sun },
  { value: "dark", label: "Dark", icon: Moon },
  { value: "system", label: "System", icon: Monitor },
]

function ModeToggle() {
  const { theme, setTheme } = useTheme()

  return (
    &lt;DropdownMenu&gt;
      &lt;DropdownMenuTrigger
        render={&lt;Button variant="ghost" aria-label="Change theme" /&gt;}
      &gt;
        &lt;Sun className="dark:hidden" /&gt;
        &lt;Moon className="hidden dark:block" /&gt;
        &lt;ChevronDown className="size-3 text-muted-foreground" /&gt;
      &lt;/DropdownMenuTrigger&gt;
      &lt;DropdownMenuContent align="end" className="min-w-36"&gt;
        &lt;DropdownMenuRadioGroup
          value={theme ?? "system"}
          onValueChange={(value) =&gt; setTheme(value as string)}
        &gt;
          {MODES.map(({ value, label, icon: Icon }) =&gt; (
            &lt;DropdownMenuRadioItem key={value} value={value}&gt;
              &lt;Icon className="text-muted-foreground" /&gt;
              {label}
            &lt;/DropdownMenuRadioItem&gt;
          ))}
        &lt;/DropdownMenuRadioGroup&gt;
      &lt;/DropdownMenuContent&gt;
    &lt;/DropdownMenu&gt;
  )
}

export { ModeToggle }
</code></pre>
<p>The menu uses a radio group so the current option is shown as selected. This makes it easier for users to see whether Light, Dark, or System is active.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/537f5bff-efb1-4a39-8eb2-5c8cd2b21cc4.png" alt="The demo header showing the theme switchers, with the custom warning-token example below." style="display: block;" width="600" height="400" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/5e0f2c2e490269cb30227a2b/5e0e37c4-76ab-4138-8574-c5e632d44f5f.png" alt="5e0e37c4-76ab-4138-8574-c5e632d44f5f" style="display: block;" width="600" height="400" loading="lazy">

<p>There are two implementation details to pay attention to here.</p>
<p>First, base UI uses <code>render</code> instead of <code>asChild</code>. The companion project uses the <code>base-nova</code> style, which is built on Base UI. In this setup, the dropdown trigger uses the <code>render</code> prop to render the shadcn button. Many older examples use <code>asChild</code>, which is common in Radix-based projects. Check your own <code>components.json</code> and component imports before copying an example.</p>
<p>Use a radio group for mutually exclusive options. Light, Dark, and System are three choices where only one can be active at a time. <code>DropdownMenuRadioGroup</code> communicates that relationship and displays the selected option.</p>
<p>The expression <code>theme ?? "system"</code> uses <code>"system"</code> as a fallback if the theme value is still undefined. This keeps the radio group controlled while <code>next-themes</code> initializes.</p>
<p>You may have seen the <code>next-themes</code> advice to wait until a component has mounted before rendering anything based on <code>theme</code>. That advice is for UI the server renders. Here, the radio items only appear when someone opens the menu, which always happens after the page has hydrated, so the server never renders a theme value and there's nothing to mismatch.</p>
<p>You can now place the switcher in your header or another part of your layout. For example:</p>
<pre><code class="language-tsx">import { ModeToggle } from "@/components/mode-toggle"

&lt;header className="flex h-14 items-center justify-between border-b px-6"&gt;
  &lt;h1 className="text-sm font-medium"&gt;My app&lt;/h1&gt;
  &lt;ModeToggle /&gt;
&lt;/header&gt;
</code></pre>
<p>Choose one switcher for your app, based on how much control you want to give users. You don't need to display both versions at once.</p>
<p>The switcher will usually sit inside a larger page, such as an account settings screen or dashboard. If you're building that kind of page, <a href="https://shadcnstudio.com/blocks">shadcn blocks</a> can give you useful layout examples. You can adapt a block to your needs and keep using the same theme tokens for its backgrounds, borders, and text.</p>
<h2 id="heading-8-why-the-icon-animation-may-not-work">8. Why the Icon Animation May Not Work</h2>
<p>You might want the sun and moon icons to rotate or scale when someone changes the theme. The shadcn examples include transition classes like these:</p>
<pre><code class="language-tsx">&lt;Sun className="scale-100 rotate-0 transition-transform dark:scale-0 dark:-rotate-90" /&gt;
&lt;Moon className="absolute scale-0 rotate-90 transition-transform dark:scale-100 dark:rotate-0" /&gt;
</code></pre>
<p>But the generated provider also uses <code>disableTransitionOnChange</code>. This option temporarily injects a stylesheet that disables transitions while the theme is changing. The rule used by the installed <code>next-themes</code> version is:</p>
<pre><code class="language-css">*,*::before,*::after{transition:none!important}
</code></pre>
<p>Because the rule uses <code>!important</code>, it can override the <code>transition-transform</code> classes on the icons during the theme change. The icons may switch immediately instead of animating.</p>
<p>There's a reason this option exists. Without it, every element with a CSS transition may animate its colors when the theme changes. Depending on your design, that can make the entire page feel slow or distracting.</p>
<p>You have a few options:</p>
<ul>
<li>Keep <code>disableTransitionOnChange</code> and use icons without transition effects.</li>
<li>Remove the option if you want the page and icons to transition together.</li>
<li>Keep the option and use a CSS animation or a motion library for the icon effect. Test this with your actual setup to make sure the animation behaves as expected.</li>
</ul>
<p>The important thing is to understand that the provider setting affects more than the theme colors. It can also affect transitions elsewhere in your interface.</p>
<h2 id="heading-9-customize-your-theme">9. Customize Your Theme</h2>
<p>Once you understand where the theme values live, changing your app's colors becomes much easier. You can update a token once and have every component that uses it pick up the new value.</p>
<h3 id="heading-change-an-existing-token">Change an Existing Token</h3>
<p>Imagine your brand uses blue as its primary color. You could set a blue background directly on one button:</p>
<pre><code class="language-tsx">&lt;Button className="bg-blue-500 dark:bg-blue-700"&gt;Save&lt;/Button&gt;
</code></pre>
<p>But this only changes that button. If you want the primary color to be consistent across your app, update the <code>--primary</code> token in <code>app/globals.css</code> instead:</p>
<pre><code class="language-css">:root {
  --primary: oklch(0.55 0.18 265);
  --primary-foreground: oklch(0.99 0 0);
}

.dark {
  --primary: oklch(0.62 0.16 265);
  --primary-foreground: oklch(0.17 0.02 265);
}
</code></pre>
<p>The same token is used by components and utilities throughout the project. Update both the <code>:root</code> and <code>.dark</code> values so the color works in both themes.</p>
<p>The two values don't have to be identical. A color that looks good on a light background may need a different lightness or saturation on a dark background. The generated theme uses different values for some tokens for exactly this reason.</p>
<p>The project also uses <code>oklch()</code> color values. In this color format, the first value represents lightness, which can make it easier to adjust how bright or dark a color appears while keeping its hue consistent.</p>
<p>You can customize the border radius in the same way. The generated <code>@theme inline</code> block derives several radius utilities from the <code>--radius</code> value, so changing it updates the overall corner scale:</p>
<pre><code class="language-css">--radius: 0.625rem;
</code></pre>
<h3 id="heading-add-a-custom-token">Add a Custom Token</h3>
<p>You can also add tokens that aren't included in the default theme. For example, let's add a <code>warning</code> color that can be used for a notice or alert.</p>
<p>First, define the token and its foreground color in both theme blocks. Then connect those variables to Tailwind in <code>@theme inline</code>:</p>
<pre><code class="language-css">:root {
  --warning: oklch(0.84 0.16 84);
  --warning-foreground: oklch(0.28 0.07 46);
}

.dark {
  --warning: oklch(0.41 0.11 46);
  --warning-foreground: oklch(0.99 0.02 95);
}

@theme inline {
  --color-warning: var(--warning);
  --color-warning-foreground: var(--warning-foreground);
}
</code></pre>
<p>You can now use the new classes in a component:</p>
<pre><code class="language-tsx">&lt;div className="bg-warning text-warning-foreground rounded-lg p-3"&gt;
  Your trial ends in 3 days.
&lt;/div&gt;
</code></pre>
<p>The component uses the same classes in both screenshots. The theme supplies the appropriate background and text colors.</p>
<p>Remember to add the <code>--color-warning</code> and <code>--color-warning-foreground</code> entries to <code>@theme inline</code>. Without those entries, the CSS variables will exist, but Tailwind won't generate the corresponding utility classes.</p>
<p>It's also a good idea to define a foreground token whenever you add a new surface color. That way, the background and text colors are designed to work together.</p>
<h3 id="heading-when-should-you-use-dark">When Should You Use <code>dark:</code></h3>
<p>Once your theme uses semantic tokens, you won't need <code>dark:</code> classes for most background and text colors.</p>
<p>For example, instead of maintaining separate light and dark background classes:</p>
<pre><code class="language-tsx">// You're now maintaining this color in two places
&lt;div className="bg-slate-100 dark:bg-slate-800"&gt;

// The token already knows
&lt;div className="bg-muted"&gt;
</code></pre>
<p>Use a semantic token such as <code>bg-muted</code> when it represents the color you want. The token already has values for both themes.</p>
<p>There are still cases where <code>dark:</code> is useful. You might need to swap an image, adjust a shadow, or change a decorative element that doesn't fit into your semantic color tokens. Use it when the appearance genuinely needs a theme-specific rule.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>A generated shadcn project already includes most of the setup needed for light and dark mode. The part you usually need to build is the switcher that gives users control over the theme.</p>
<p>Here's a quick recap:</p>
<ol>
<li><code>:root</code> and <code>.dark</code> define the theme values. They use the same variable names with different values.</li>
<li><code>@theme inline</code> connects CSS variables to Tailwind utilities**.** Add a matching entry when you create a custom token.</li>
<li><code>next-themes</code> applies the active theme. In this setup, it adds or removes the <code>dark</code> class on <code>&lt;html&gt;</code>.</li>
<li>The generated project already includes the provider. Check <code>components/theme-provider.tsx</code> and <code>app/layout.tsx</code> before creating another one.</li>
<li>The visible switcher is the part you add. Use a simple toggle or a menu with Light, Dark, and System options.</li>
<li>Customize tokens instead of styling every component separately. This keeps your colors consistent across the app.</li>
</ol>
<p>Once you know how these pieces fit together, dark mode becomes easier to maintain. You can update the theme in one place, add new tokens when you need them, and let your components use those values without having to check which theme is active.</p>
<h2 id="heading-references">References</h2>
<ul>
<li><a href="https://ui.shadcn.com/create">shadcn/create</a>: Generate a shadcn project.</li>
<li><a href="https://ui.shadcn.com/docs/dark-mode/next">shadcn dark mode for Next.js</a>: Official Next.js dark-mode setup.</li>
<li><a href="https://ui.shadcn.com/docs/theming">shadcn theming</a>: Theme tokens and CSS variables.</li>
<li><a href="https://github.com/pacocoursey/next-themes">next-themes</a>: Theme provider documentation and source.</li>
<li><a href="https://tailwindcss.com/docs/theme">Tailwind CSS theme variables</a>: How theme variables create utility classes.</li>
<li><a href="https://base-ui.com/">Base UI</a>: Documentation for the primitives used by the <code>base-nova</code> style.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/color_value/oklch">MDN: <code>oklch()</code></a>: Reference for the OKLCH color format.</li>
</ul>
<h4 id="heading-thanks-for-reading">Thanks for Reading</h4>
<p>The companion project includes both switcher examples, the custom <code>warning</code> token, and the page used for the screenshots. To try the examples locally, clone the repository, then run <code>pnpm install</code> followed by <code>pnpm dev</code> from the project directory.</p>
<p>Companion GitHub repository:- <a href="https://github.com/shadcnstudio/shadcn-dark-mode-guide">https://github.com/shadcnstudio/shadcn-dark-mode-guide</a></p>
<p>If you try the examples and run into something that behaves differently in your setup, leave a comment with your shadcn style and package versions. That context makes it much easier to work out what's happening.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Phishing Attacks Actually Work (And How Developers Can Spot Them) ]]>
                </title>
                <description>
                    <![CDATA[ Phishing attacks are getting harder to recognize. And no, it isn't just because hackers have become better at hiding spelling mistakes. Some phishing emails now look almost identical to genuine securi ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-phishing-attacks-work/</link>
                <guid isPermaLink="false">6b061084d3cd7eb63b3e05fa</guid>
                
                    <category>
                        <![CDATA[ cybersecurity ]]>
                    </category>
                
                    <category>
                        <![CDATA[ phishing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reetain Raina ]]>
                </dc:creator>
                <pubDate>Tue, 24 Nov 2026 22:32:36 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/cb02608a-4ac9-48f2-8d81-5c5684ab9892.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Phishing attacks are getting harder to recognize. And no, it isn't just because hackers have become better at hiding spelling mistakes. Some phishing emails now look almost identical to genuine security alerts, complete with familiar company logos, professional language, and links that take you to websites that look exactly like the real thing.</p>
<p>You might think you're logging into your GitHub account to fix a security issue, when you're actually giving your login details to someone else. That's not exactly the kind of account activity you want.</p>
<p>The interesting part is that attackers don't always need to find a weakness in an application's code. Sometimes, convincing a person to share their password is all it takes. This is where social engineering comes in, combining human behaviour with technical tricks to steal sensitive information.</p>
<p>In this article, we'll break down how phishing attacks actually work and look at the different techniques attackers use. We'll also understand how developers can spot suspicious URLs, inspect email authentication, and protect their applications from credential theft. Then we'll look at what happens behind a fake login page and why even that little HTTPS padlock isn't a guarantee that a website is safe.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-what-is-a-phishing-attack-and-why-does-it-work">What Is a Phishing Attack and Why Does It Work?</a><ul>
<li><a href="#heading-phishing-is-more-about-human-behavior-than-hacking">Phishing Is More About Human Behavior Than Hacking</a></li>
<li><a href="#heading-why-people-fall-for-phishing-messages">Why People Fall for Phishing Messages</a></li>
</ul>
</li>
<li><a href="#heading-how-phishing-attacks-actually-work-a-step-by-step-breakdown">How Phishing Attacks Actually Work: A Step-by-Step Breakdown</a><ul>
<li><a href="#heading-step-1-the-attacker-chooses-a-target">Step 1: The Attacker Chooses a Target</a></li>
<li><a href="#heading-step-2-the-attacker-creates-a-convincing-message">Step 2: The Attacker Creates a Convincing Message</a></li>
<li><a href="#heading-step-3-the-victim-clicks-a-fake-link">Step 3: The Victim Clicks a Fake Link</a></li>
<li><a href="#heading-step-4-the-fake-website-collects-information">Step 4: The Fake Website Collects Information</a></li>
<li><a href="#heading-step-5-the-attacker-uses-the-stolen-credentials">Step 5: The Attacker Uses the Stolen Credentials</a></li>
</ul>
</li>
<li><a href="#heading-the-different-types-of-phishing-attacks-developers-should-know">The Different Types of Phishing Attacks Developers Should Know</a><ul>
<li><a href="#heading-email-phishing">Email Phishing</a></li>
<li><a href="#heading-spear-phishing">Spear Phishing</a></li>
<li><a href="#heading-clone-phishing">Clone Phishing</a></li>
<li><a href="#heading-smishing-and-vishing">Smishing and Vishing</a></li>
<li><a href="#heading-business-email-compromise-bec">Business Email Compromise (BEC)</a></li>
</ul>
</li>
<li><a href="#heading-how-developers-can-spot-a-phishing-attack">How Developers Can Spot a Phishing Attack</a><ul>
<li><a href="#heading-inspect-the-url-before-trusting-the-website">Inspect the URL Before Trusting the Website</a></li>
<li><a href="#heading-check-the-email-headers-and-sender-information">Check the Email Headers and Sender Information</a></li>
<li><a href="#heading-look-for-suspicious-login-behavior">Look for Suspicious Login Behavior</a></li>
<li><a href="#heading-examine-links-and-attachments-carefully">Examine Links and Attachments Carefully</a></li>
</ul>
</li>
<li><a href="#heading-a-developers-perspective-what-happens-behind-a-phishing-login-page">A Developer's Perspective: What Happens Behind a Phishing Login Page?</a><ul>
<li><a href="#heading-understanding-a-normal-login-request">Understanding a Normal Login Request</a></li>
</ul>
</li>
<li><a href="#heading-what-makes-a-phishing-login-page-different">What Makes a Phishing Login Page Different?</a><ul>
<li><a href="#heading-why-https-does-not-make-a-phishing-website-safe">Why HTTPS Does Not Make a Phishing Website Safe</a></li>
</ul>
</li>
<li><a href="#heading-how-developers-can-protect-their-applications-from-phishing-attacks">How Developers Can Protect Their Applications From Phishing Attacks</a><ul>
<li><a href="#heading-implement-multi-factor-authentication-mfa">Implement Multi-Factor Authentication (MFA)</a></li>
<li><a href="#heading-use-secure-authentication-practices">Use Secure Authentication Practices</a></li>
<li><a href="#heading-validate-redirects-and-external-urls">Validate Redirects and External URLs</a></li>
<li><a href="#heading-configure-email-authentication">Configure Email Authentication</a></li>
</ul>
</li>
<li><a href="#heading-what-should-you-do-if-you-accidentally-click-a-phishing-link">What Should You Do If You Accidentally Click a Phishing Link?</a><ul>
<li><a href="#heading-if-you-only-clicked-the-link">If You Only Clicked the Link</a></li>
<li><a href="#heading-if-you-entered-your-credentials">If You Entered Your Credentials</a></li>
<li><a href="#heading-report-the-phishing-attempt">Report the Phishing Attempt</a></li>
</ul>
</li>
<li><a href="#heading-final-thoughts">Final Thoughts</a></li>
</ul>
<h2 id="heading-what-is-a-phishing-attack-and-why-does-it-work">What Is a Phishing Attack and Why Does It Work?</h2>
<p>Phishing is fundamentally a psychological exploit wrapped in a technological delivery system. Before looking at the code and infrastructure involved, you need to understand the human elements that make these attacks so consistently successful.</p>
<h3 id="heading-phishing-is-more-about-human-behavior-than-hacking">Phishing Is More About Human Behavior Than Hacking</h3>
<p>At its core, phishing is a form of social engineering. Attackers impersonate trusted people, companies, or services to manipulate their targets. Their primary objective is usually to steal login credentials, harvest financial information or gain initial access to restricted systems.</p>
<p>Rather than searching for a vulnerability in a firewall, the attacker searches for a vulnerability in human judgment. They manufacture situations designed to bypass critical thinking, relying on specific emotional triggers to influence the victim's decisions.</p>
<h3 id="heading-why-people-fall-for-phishing-messages">Why People Fall for Phishing Messages</h3>
<p>The science behind why intelligent people fall for these scams comes down to cognitive load and neurobiology. When a person reads a message demanding immediate action, the brain's amygdala, responsible for processing fear and urgency, often overrides the prefrontal cortex, which handles logical analysis.</p>
<p>Attackers weaponize this biological response using several common triggers. They create urgency by claiming an account will be suspended if the user doesn't act immediately. They leverage fear by suggesting someone has already compromised the victim's data. They project authority by spoofing emails from a manager or an IT administrator. Alternatively, they spark curiosity by vaguely mentioning the victim in a shared document.</p>
<p>Technical knowledge doesn't automatically make someone immune to this kind of psychological manipulation. The <a href="https://www.verizon.com/business/resources/reports/dbir/"><u>Verizon 2025 Data Breach Investigations Report</u></a> consistently demonstrates that the human element, including social engineering and credential abuse, remains a primary catalyst in the vast majority of security breaches. When a developer is tired, distracted or managing a high cognitive load, a well-crafted fake alert can easily slip past their regular defenses.</p>
<h2 id="heading-how-phishing-attacks-actually-work-a-step-by-step-breakdown">How Phishing Attacks Actually Work: A Step-by-Step Breakdown</h2>
<p>To truly understand the threat, developers need to see the lifecycle of an attack. Consider a fictional, yet highly realistic, phishing campaign targeting a developer's GitHub account.</p>
<h3 id="heading-step-1-the-attacker-chooses-a-target">Step 1: The Attacker Chooses a Target</h3>
<p>Attackers rarely send emails completely at random when targeting high-value infrastructure. They actively identify potential victims by scraping public information. A developer with a public GitHub profile, an active LinkedIn presence, and a personal portfolio website is an ideal target.</p>
<p>The attacker compiles this publicly available data to understand what tools the developer uses, which repositories they contribute to, and what their primary email address is. This reconnaissance phase ensures the eventual payload is contextually relevant and highly believable.</p>
<h3 id="heading-step-2-the-attacker-creates-a-convincing-message">Step 2: The Attacker Creates a Convincing Message</h3>
<p>Using the gathered intelligence, the attacker crafts an email impersonating a trusted service. The developer receives an email claiming their GitHub account has been flagged for suspicious activity originating from an unknown IP address. To make the illusion complete, the attacker flawlessly imitates GitHub's branding, layout, typography, and terminology.</p>
<p>The email contains a prominent call-to-action button urging the developer to "Verify Account Activity." Because the message aligns with standard security alert protocols, the developer's initial suspicion is naturally lowered.</p>
<h3 id="heading-step-3-the-victim-clicks-a-fake-link">Step 3: The Victim Clicks a Fake Link</h3>
<p>When the developer clicks the verification button, they're directed to a fraudulent website. This is where domain manipulation comes into play. The attacker will use lookalike domains, subtle misspellings, or misleading subdomains to disguise the destination.</p>
<p>For instance, the URL might read <a href="http://github.com">github.com</a>.example-login.test. While the word "github" is present, the actual domain being accessed is example-login.test. Attackers also exploit URL redirects or utilize homograph attacks, where Cyrillic or unexpected Unicode characters replace standard Latin letters to create visually identical, yet fundamentally different, URLs.</p>
<h3 id="heading-step-4-the-fake-website-collects-information">Step 4: The Fake Website Collects Information</h3>
<p>When they land on the fake website, the victim encounters a perfect clone of the legitimate login screen. When the developer enters their username and password, the browser doesn't send this data to GitHub's authentication servers. Instead, the fake login form executes a script that packages the credentials and transmits them directly to an attacker-controlled server.</p>
<p>According to comprehensive analysis in the Google Research paper <a href="https://research.google/pubs/data-breaches-phishing-or-malware-understanding-the-risks-of-stolen-credentials/"><u>Data Breaches, Phishing or Malware? Understanding the Risks of Stolen Credentials</u></a>, stolen credentials are often tested or sold within hours, if not minutes, of being harvested.</p>
<h3 id="heading-step-5-the-attacker-uses-the-stolen-credentials">Step 5: The Attacker Uses the Stolen Credentials</h3>
<p>Once the attacker possesses the compromised credentials, the fallout is immediate. They use the stolen username and password to log into the real GitHub platform. From there, they can access private repositories, inject malicious code into production branches, or extract exposed API keys and environment secrets.</p>
<p>Also, because password reuse is incredibly common, the attacker will likely test these same credentials against the developer's email, cloud hosting provider and internal company portals, exponentially increasing the effect of a single mistaken click.</p>
<h2 id="heading-the-different-types-of-phishing-attacks-developers-should-know">The Different Types of Phishing Attacks Developers Should Know</h2>
<p>While the GitHub scenario illustrates a standard attack, threat actors utilize several variations depending on their goals and resources. Understanding these variations helps in identifying the specific vector being used.</p>
<h3 id="heading-email-phishing">Email Phishing</h3>
<p>This is the traditional approach involving fake emails distributed to a large number of recipients. These campaigns cast a wide net, impersonating ubiquitous services like banks, package delivery companies, or software platforms, hoping a small percentage of recipients will engage with the malicious links.</p>
<h3 id="heading-spear-phishing">Spear Phishing</h3>
<p>Unlike mass email campaigns, spear phishing is a highly targeted attack designed for a specific individual or organization. Attackers leverage detailed information about a person's job role, current projects, colleagues, or preferred software tools to make the message incredibly believable.</p>
<p>A spear-phishing email might reference a specific Jira ticket or a recent deployment, making it nearly indistinguishable from legitimate internal communication.</p>
<h3 id="heading-clone-phishing">Clone Phishing</h3>
<p>In a clone phishing attack, the adversary intercepts or acquires a legitimate email that was previously delivered. They create an exact replica of this email but replace the original safe links or attachments with malicious ones. Because the recipient recognizes the context and the sender of the original conversation, they are highly likely to trust the cloned version.</p>
<h3 id="heading-smishing-and-vishing">Smishing and Vishing</h3>
<p>Phishing isn't confined to the inbox. Smishing involves sending malicious links or urgent alerts through SMS text messages. Vishing relies on voice calls, where the attacker uses social engineering over the phone, often utilizing AI voice-cloning technology to extract passwords or multi-factor authentication codes directly from the victim.</p>
<h3 id="heading-business-email-compromise-bec">Business Email Compromise (BEC)</h3>
<p>BEC is a sophisticated financial attack where threat actors impersonate executives, managers, or vendors. The goal is rarely to steal a password. Instead, they trick employees into authorizing fraudulent wire transfers, modifying payroll details, or sharing sensitive corporate data.</p>
<p>The <a href="https://docs.apwg.org/"><u>APWG Phishing Activity Trends Report</u></a> routinely highlights BEC as one of the most financially devastating forms of social engineering targeting modern enterprises.</p>
<h2 id="heading-how-developers-can-spot-a-phishing-attack">How Developers Can Spot a Phishing Attack</h2>
<p>Moving beyond general security awareness, developers have the technical literacy to inspect the underlying mechanics of a suspicious message. Identifying phishing requires analyzing the structural components of web traffic and email protocols.</p>
<h3 id="heading-inspect-the-url-before-trusting-the-website">Inspect the URL Before Trusting the Website</h3>
<p>The most reliable way to identify a fraudulent website is by dissecting its URL. Attackers rely on the fact that most users only glance at the address bar. Developers should look for lookalike domains, unexpected subdomains, and URL shorteners designed to hide the final destination.</p>
<p>It's crucial to identify the actual root domain serving the page. For example, <a href="https://github.com/login">https://github.com/login</a> is the legitimate endpoint. In contrast, <a href="https://github-login.example.com">https://github-login.example.com</a> and <a href="https://github.com.example.net/login">https://github.com.example.net/login</a> both resolve to attacker-controlled domains, regardless of the presence of the word "github."</p>
<p>Studies analyzing automated detection systems, such as research on <a href="https://arxiv.org/abs/2103.01168"><u>Evaluating the Robustness of Phishing Web Page Detection Models</u></a>, emphasize that analyzing lexical features and domain registration anomalies remains one of the most effective ways to identify malicious infrastructure.</p>
<h3 id="heading-check-the-email-headers-and-sender-information">Check the Email Headers and Sender Information</h3>
<p>Display names in email clients are easily forged, but email headers reveal the actual routing path. Developers should inspect the From, Reply-To, and Return-Path addresses for discrepancies.</p>
<p>More importantly, checking the authentication headers provides important insight. SPF (Sender Policy Framework) verifies that the sending server is authorized by the domain owner. DKIM (DomainKeys Identified Mail) uses cryptographic signatures to ensure the email content has not been altered in transit. DMARC (Domain-based Message Authentication, Reporting and Conformance) ties SPF and DKIM together, dictating how receivers should handle emails that fail these checks.</p>
<p>While passing these checks doesn't guarantee absolute safety, failing them is a massive red flag.</p>
<h3 id="heading-look-for-suspicious-login-behavior">Look for Suspicious Login Behavior</h3>
<p>Context is just as important as the technical indicators. Developers should constantly question unexpected authentication prompts.</p>
<p>If you receive a password reset notification you didn't request or a multi-factor authentication (MFA) approval prompt for a session you didn't initiate, an attacker is likely testing your credentials.</p>
<p>Similarly, any service demanding that you manually share API keys, session tokens, or passwords through a chat interface or email should be immediately classified as hostile.</p>
<h3 id="heading-examine-links-and-attachments-carefully">Examine Links and Attachments Carefully</h3>
<p>Malicious payloads are frequently hidden within attachments. Unexpected executable files are obvious threats, but unusual document attachments, such as PDFs or Office files containing embedded macros, are equally dangerous. Links should always match the contextual premise of the message.</p>
<p>It's important to emphasize that spelling mistakes and grammatical errors are no longer a reliable metric for identifying phishing. With the advent of generative AI, modern phishing emails are often impeccably written and flawlessly formatted.</p>
<h2 id="heading-a-developers-perspective-what-happens-behind-a-phishing-login-page">A Developer's Perspective: What Happens Behind a Phishing Login Page?</h2>
<p>To fully grasp the danger, it helps to look at the attack from an architectural perspective. The difference between a legitimate authentication flow and a credential harvesting operation comes down to data destination.</p>
<h3 id="heading-understanding-a-normal-login-request">Understanding a Normal Login Request</h3>
<p>When a user logs into a legitimate modern web application, the frontend collects the input and transmits it via an asynchronous HTTP request. A simplified example looks like this:</p>
<pre><code class="language-javascript">async function login(email, password) {
  const response = await fetch("/api/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      email,
      password
    })
  });

  return response.json();
}
</code></pre>
<p>In this legitimate flow, the browser sends the POST request to the official backend API. The server validates the credentials against a securely hashed database entry, generates a session token or cookie, and responds with an authentication success result.</p>
<h2 id="heading-what-makes-a-phishing-login-page-different">What Makes a Phishing Login Page Different?</h2>
<p>A phishing page entirely bypasses this established backend. While the HTML and CSS create a familiar visual interface, the underlying JavaScript is fundamentally different. Instead of sending the payload to /api/login on the official domain, the script submits the entered information to an external, attacker-controlled endpoint. The user interacts with the fake interface and the POST request quietly ships their plaintext credentials to a remote database.</p>
<p>After the data is stolen, the script typically redirects the victim to the real website's legitimate login page, leaving them confused but unaware that a theft just occurred.</p>
<h3 id="heading-why-https-does-not-make-a-phishing-website-safe">Why HTTPS Does Not Make a Phishing Website Safe</h3>
<p>There's a persistent misconception that the padlock icon in the browser address bar signifies that a website is trustworthy. This is technologically false. HTTPS simply means the communication channel between the browser and the web server is secure. Just because a website uses encryption, much like how an <a href="https://proton.me/mail"><u>encrypted email like Proton Mail</u></a> protects your personal messages from outside snooping during transit, it doesn't verify the actual identity of the person operating the server on the other end.</p>
<p>Attackers can easily and freely obtain valid TLS certificates for their malicious domains. Ultimately, a phishing site equipped with HTTPS simply ensures that your credentials are stolen securely, preventing third-party eavesdroppers on the network from intercepting the data before the phisher receives it.</p>
<h2 id="heading-how-developers-can-protect-their-applications-from-phishing-attacks">How Developers Can Protect Their Applications From Phishing Attacks</h2>
<p>Identifying phishing as an end-user is only half the battle. Developers are uniquely positioned to architect systems that mitigate the impact of phishing attacks against their own user base.</p>
<h3 id="heading-implement-multi-factor-authentication-mfa">Implement Multi-Factor Authentication (MFA)</h3>
<p>Passwords alone are an insufficient defense against credential harvesting. Implementing MFA adds a distinct verification layer.</p>
<p>But not all MFA is created equal. SMS-based codes can be intercepted and simple push notifications are vulnerable to "MFA fatigue" attacks, where adversaries spam the user until they accidentally approve a request.</p>
<p>Developers should prioritize phishing-resistant authentication methods, such as hardware security keys (like YubiKeys) or WebAuthn/Passkey implementations, which cryptographically bind the authentication attempt to the legitimate domain, making stolen passwords useless.</p>
<h3 id="heading-use-secure-authentication-practices">Use Secure Authentication Practices</h3>
<p>Application security fundamentally requires robust backend practices. Passwords must never be stored in plain text they must be hashed using strong, salted algorithms like bcrypt or Argon2.</p>
<p>Developers should implement aggressive rate limiting on login endpoints to prevent credential stuffing attacks using previously phished password lists. Also, session management should be ironclad, utilizing HttpOnly and Secure flags on cookies to prevent cross-site scripting (XSS) from exposing authentication tokens.</p>
<h3 id="heading-validate-redirects-and-external-urls">Validate Redirects and External URLs</h3>
<p>Improperly configured redirect mechanisms often inadvertently assist phishing campaigns. If a web application uses unvalidated input to determine where to send a user after login (an "open redirect" vulnerability), attackers can craft a link to the legitimate site that automatically forwards the user to a malicious clone.</p>
<p>Developers should strictly validate redirect destinations against an internal allowlist, especially during authentication and password reset workflows.</p>
<h3 id="heading-configure-email-authentication">Configure Email Authentication</h3>
<p>To prevent attackers from easily spoofing the application's official email domain, developers and operations teams should configure DNS-based email authentication. Implementing SPF, DKIM, and DMARC creates a verifiable chain of trust.</p>
<p>As outlined in the <a href="https://csrc.nist.gov/publications/detail/sp/800-177/rev-1/final"><u>NIST Phishing Guidance</u></a>, these protocols are essential for reducing domain spoofing. While they won't stop an attacker from registering a lookalike domain, they will stop them from sending emails that appear to originate exactly from your actual company servers.</p>
<h2 id="heading-what-should-you-do-if-you-accidentally-click-a-phishing-link">What Should You Do If You Accidentally Click a Phishing Link?</h2>
<p>Even the most vigilant developers can make a mistake during a stressful deployment or a chaotic workday. Knowing what your incident response plan is and how to execute it right away is crucial for containment.</p>
<h3 id="heading-if-you-only-clicked-the-link">If You Only Clicked the Link</h3>
<p>If you click a suspicious link but immediately recognize the threat before entering any data, close the browser tab immediately. Don't interact with the page, avoid downloading any files, and certainly don't accept any browser permission requests.</p>
<p>The <a href="https://www.cyber.gc.ca/en/guidance/dont-take-bait-recognize-and-avoid-phishing-attacks"><u>Canadian Centre for Cyber Security</u></a> notes that simply clicking a link doesn't automatically mean your machine is infected, provided your browser and operating system are fully updated. But if a file automatically downloaded or executed, you should disconnect from the network and follow your organization's formal incident response procedure.</p>
<h3 id="heading-if-you-entered-your-credentials">If You Entered Your Credentials</h3>
<p>If you typed your password and hit submit, assume the credentials are compromised instantly. Navigate directly to the official website by typing the URL yourself and change your password immediately.</p>
<p>If the application allows it, manually revoke all active sessions. Review your recent login history for unrecognized IP addresses. If you haven't already, enable a phishing-resistant MFA method. And if you reused that exact password on any other service, you'll need change it on those platforms as well.</p>
<h3 id="heading-report-the-phishing-attempt">Report the Phishing Attempt</h3>
<p>Reporting is a critical community defense mechanism. Notify your internal security or IT team immediately so they can investigate the domain, block the malicious IP addresses at the firewall, and alert other employees who may have received the same message. Ignoring the mistake only gives the attacker more time to exploit the access they just gained.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>Phishing is a reminder that breaking into an account doesn't always require breaking into its code. Sometimes, all it takes is a convincing email, a familiar-looking login page, and a moment when someone isn't paying enough attention.</p>
<p>That's what makes these attacks interesting from a security perspective. They target both the technology we build and the people who use it. Developers can make authentication stronger, protect sensitive data, and close security gaps, but they also need to understand how attackers exploit human behaviour. Because at the end of the day, a secure application keeps hackers out and also doesn't make things easy for them when someone accidentally lets them in.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Browser-Based PDF Password Protector Using JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Contracts, invoices, medical reports, and scanned ID cards are often converted to PDF files. And if one of them ends up in the wrong inbox or on a shared drive, anyone can open it. Adding a password f ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-pdf-password-protector-javascript/</link>
                <guid isPermaLink="false">6aff2ffbede28e00513a0715</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pdf ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Security ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ encryption ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavin Sheth ]]>
                </dc:creator>
                <pubDate>Thu, 19 Nov 2026 17:20:58 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/3ad5640f-31b1-412d-a20c-d1180ae363f2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Contracts, invoices, medical reports, and scanned ID cards are often converted to PDF files. And if one of them ends up in the wrong inbox or on a shared drive, anyone can open it.</p>
<p>Adding a password fixes that. A protected PDF is encrypted, so the file is unreadable until someone types the right password.</p>
<p>Most online tools that do this ask you to upload the document first. But that's an odd thing to do with a file you're trying to keep private.</p>
<p>In this tutorial, you'll build a browser-based PDF password protector with JavaScript. You'll open a PDF, choose a password, decide whether people can print, copy or edit it, encrypt the file with AES-256, check the result, and download it. The file never leaves the browser.</p>
<p>The interesting part is that the most popular JavaScript PDF library, PDF-lib, can't encrypt PDFs. So you'll write the encryption yourself with the Web Crypto API, following the PDF 2.0 specification. It's less code than you might expect: about 150 lines.</p>
<p>I built this tool for <a href="https://allinonetools.net/">All In One Tools</a>, where it runs as the Protect PDF tool. This article walks through a simplified version that you can build in three files.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/25eafe88-cf76-45b8-8411-949d202f2ac6.png" alt="Protect PDF tool on All In One Tools, showing the drop area for adding a PDF" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a href="#heading-what-this-pdf-protector-does">What This PDF Protector Does</a></li>
<li><a href="#heading-how-pdf-encryption-works">How PDF Encryption Works</a></li>
<li><a href="#heading-project-setup">Project Setup</a></li>
<li><a href="#heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</a></li>
<li><a href="#heading-creating-the-html-layout">Creating the HTML Layout</a></li>
<li><a href="#heading-opening-the-pdf">Opening the PDF</a></li>
<li><a href="#heading-handling-the-password-fields">Handling the Password Fields</a></li>
<li><a href="#heading-helpers-for-bytes-and-web-crypto">Helpers for Bytes and Web Crypto</a></li>
<li><a href="#heading-hashing-the-password-the-pdf-20-way">Hashing the Password the PDF 2.0 Way</a></li>
<li><a href="#heading-turning-permissions-into-a-number">Turning Permissions into a Number</a></li>
<li><a href="#heading-building-the-encryption-keys">Building the Encryption Keys</a></li>
<li><a href="#heading-encrypting-every-string-and-stream">Encrypting Every String and Stream</a></li>
<li><a href="#heading-writing-the-protected-pdf">Writing the Protected PDF</a></li>
<li><a href="#heading-checking-the-result-with-pdfjs">Checking the Result with PDF.js</a></li>
<li><a href="#heading-connecting-the-button">Connecting the Button</a></li>
<li><a href="#heading-renaming-and-downloading">Renaming and Downloading</a></li>
<li><a href="#heading-testing-the-file-outside-the-browser">Testing the File Outside the Browser</a></li>
<li><a href="#heading-demo-how-the-protect-pdf-tool-works">Demo: How the Protect PDF Tool Works</a></li>
<li><a href="#heading-performance-tips">Performance Tips</a></li>
<li><a href="#heading-common-mistakes">Common Mistakes</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-this-pdf-protector-does">What This PDF Protector Does</h2>
<p>The finished tool lets you open a PDF by clicking a button or dropping the file on the page. You can type a password that will be needed to open the file (and optionally type a second password for the permissions). You can also choose whether people can print, copy text and images, or edit the file.</p>
<p>The tool also encrypts the PDF with AES-256, checks that the new file really asks for a password and opens it with yours, and lets you rename and download the protected copy.</p>
<p>Through all this, the original file is never changed, and nothing is sent to a server.</p>
<h2 id="heading-how-pdf-encryption-works">How PDF Encryption Works</h2>
<p>Before writing our code, it helps to know what a protected PDF looks like inside. You don't need to read the specification, but these five ideas will make the rest of the article easier to follow.</p>
<h3 id="heading-1-the-content-is-encrypted-the-structure-isnt">1. The Content is Encrypted, the Structure Isn't</h3>
<p>A PDF is a list of numbered objects: dictionaries, arrays, numbers, names, strings and streams (a stream is a block of data, such as the drawing instructions of a page or an image). When a PDF is protected, every <strong>string</strong> and every <strong>stream</strong> is encrypted. Numbers, names and the way objects point to each other stay readable, so a PDF reader can still find its way around the file.</p>
<h3 id="heading-2-one-random-key-encrypts-everything">2. One Random Key Encrypts Everything</h3>
<p>The tool creates a random 256-bit file key and encrypts all strings and streams with it using AES. The password isn't the key.</p>
<h3 id="heading-3-the-password-unlocks-the-key">3. The Password Unlocks the Key</h3>
<p>The file stores the file key twice, encrypted with a hash of each password, plus a value that lets a reader check whether a typed password is right. These values live in an encryption dictionary, and the file's trailer points to it with <code>/Encrypt</code>.</p>
<h3 id="heading-4-there-are-two-passwords">4. There Are Two Passwords</h3>
<ul>
<li>The <strong>user password</strong> (the open password) is needed to open the file.</li>
<li>The <strong>owner password</strong> (the permissions password) unlocks the file <em>and</em> lets the owner change what's allowed.</li>
</ul>
<h3 id="heading-5-permissions-arent-a-lock"><strong>5. Permissions Aren't a Lock</strong></h3>
<p>The allowed actions (print, copy, edit) are stored as bits in a number called <code>/P</code>. Good PDF readers obey them, but a program that ignores them can still print or copy once the file is open. The open password is what really protects the content.</p>
<p>PDF has used several encryption methods over the years:</p>
<table>
<thead>
<tr>
<th>Method</th>
<th>Revision</th>
<th>Status</th>
</tr>
</thead>
<tbody><tr>
<td>RC4 40-bit and 128-bit</td>
<td>R2 to R4</td>
<td>Old and weak, don't use them for new files</td>
</tr>
<tr>
<td>AES-128</td>
<td>R4</td>
<td>Opens in Acrobat 7 and newer</td>
</tr>
<tr>
<td>AES-256</td>
<td>R6</td>
<td>PDF 2.0 standard, opens in Acrobat X and newer and in all current PDF apps</td>
</tr>
</tbody></table>
<p>This tool uses <strong>AES-256 (revision 6)</strong>. It's the strongest option, and it's also the simplest to build, because every object uses the same key.</p>
<p>Let's go through the flow.</p>
<p>From the PDF file:</p>
<ul>
<li>PDF-lib loads the objects</li>
<li>random file key (32 bytes)</li>
<li>U, UE, O, OE, Perms from the passwords (SHA-2 + AES)</li>
<li>every string and stream is encrypted with AES-256</li>
<li>/Encrypt dictionary + /ID are added to the trailer</li>
<li>the saved PDF is checked with PDF.js and then downloaded</li>
</ul>
<h2 id="heading-project-setup">Project Setup</h2>
<p>The project is three files and has no build step:</p>
<pre><code class="language-text">pdf-protector/
├── index.html
├── style.css
└── script.js
</code></pre>
<p>Because the Web Crypto API only works in a secure context, open the page from <code>https://</code> or from <code>http://localhost</code>. If you open <code>index.html</code> with a <code>file://</code> path or a plain <code>http://</code> address, <code>crypto.subtle</code> is <code>undefined</code>.</p>
<p>The easiest way to get a local server is:</p>
<pre><code class="language-bash">npx serve .
</code></pre>
<p>Then open the address it prints, such as <code>http://localhost:3000</code>.</p>
<h2 id="heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</h2>
<p><a href="https://pdf-lib.js.org/"><strong>PDF-lib</strong></a> <strong>1.17.1</strong> reads the PDF into objects you can change and writes it back out. It doesn't support encryption, which is why you'll build that part.</p>
<p><a href="https://mozilla.github.io/pdf.js/"><strong>PDF.js</strong></a> <strong>3.11.174</strong> is Mozilla's PDF reader. You'll use it to open the protected file, the same way a real reader would, and confirm that it works.</p>
<p><strong>The</strong> <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API"><strong>Web Crypto API</strong></a> is built into every modern browser. It gives you AES encryption, SHA-256/384/512 hashes, and secure random numbers. Never use <code>Math.random()</code> for keys.</p>
<p>Both libraries load from a CDN at the end of <code>index.html</code>:</p>
<pre><code class="language-html">&lt;script src="https://unpkg.com/pdf-lib@1.17.1/dist/pdf-lib.min.js"&gt;&lt;/script&gt;
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js"&gt;&lt;/script&gt;
&lt;script src="script.js"&gt;&lt;/script&gt;
</code></pre>
<h2 id="heading-creating-the-html-layout">Creating the HTML Layout</h2>
<p>The page has three parts: an upload area, a settings panel with the passwords and permissions, and a result panel. The settings and result panels start hidden.</p>
<pre><code class="language-html">&lt;!-- 1. Upload --&gt;
&lt;section id="uploadArea" class="upload-area"&gt;
  &lt;p&gt;Drop a PDF here or&lt;/p&gt;
  &lt;button type="button" id="selectBtn"&gt;Select PDF&lt;/button&gt;
  &lt;input type="file" id="fileInput" accept="application/pdf,.pdf" hidden&gt;
  &lt;p id="fileInfo" class="file-info" aria-live="polite"&gt;&lt;/p&gt;
&lt;/section&gt;

&lt;!-- 2. Passwords --&gt;
&lt;section id="settings" class="panel" hidden&gt;
  &lt;h2&gt;Passwords&lt;/h2&gt;

  &lt;label for="openPw"&gt;Password to open the PDF&lt;/label&gt;
  &lt;div class="pw-row"&gt;
    &lt;input type="password" id="openPw" autocomplete="new-password"&gt;
    &lt;button type="button" class="show-btn" data-target="openPw"&gt;Show&lt;/button&gt;
  &lt;/div&gt;
  &lt;p id="strength" class="hint"&gt;Use at least 8 characters.&lt;/p&gt;

  &lt;label for="openPw2"&gt;Type the password again&lt;/label&gt;
  &lt;input type="password" id="openPw2" autocomplete="new-password"&gt;

  &lt;label for="ownerPw"&gt;Permissions password (optional)&lt;/label&gt;
  &lt;div class="pw-row"&gt;
    &lt;input type="password" id="ownerPw" autocomplete="new-password"&gt;
    &lt;button type="button" class="show-btn" data-target="ownerPw"&gt;Show&lt;/button&gt;
  &lt;/div&gt;
  &lt;p class="hint"&gt;Lets you change the restrictions below later. Leave it empty to use a random one.&lt;/p&gt;

  &lt;h2&gt;What can people do after opening it?&lt;/h2&gt;
  &lt;label class="check"&gt;&lt;input type="checkbox" id="allowPrint" checked&gt; Print&lt;/label&gt;
  &lt;label class="check"&gt;&lt;input type="checkbox" id="allowCopy" checked&gt; Copy text and images&lt;/label&gt;
  &lt;label class="check"&gt;&lt;input type="checkbox" id="allowEdit"&gt; Edit, comment and fill forms&lt;/label&gt;

  &lt;button type="button" id="protectBtn" class="primary"&gt;Protect PDF&lt;/button&gt;
  &lt;p id="status" class="status" aria-live="polite"&gt;&lt;/p&gt;
&lt;/section&gt;

&lt;!-- 3. Result --&gt;
&lt;section id="result" class="panel" hidden&gt;
  &lt;h2&gt;Your protected PDF is ready&lt;/h2&gt;
  &lt;ul id="checks" class="checks"&gt;&lt;/ul&gt;
  &lt;label for="fileName"&gt;File name&lt;/label&gt;
  &lt;input type="text" id="fileName"&gt;
  &lt;button type="button" id="downloadBtn" class="primary"&gt;Download PDF&lt;/button&gt;
&lt;/section&gt;
</code></pre>
<p>There are a few details worth pointing out here:</p>
<ul>
<li>The password inputs use <code>autocomplete="new-password"</code>, so the browser doesn't fill in a saved login password.</li>
<li>The status lines use <code>aria-live="polite"</code>, so screen readers announce messages such as "The two passwords are different."</li>
<li>The file input is hidden. A regular button opens it, which is easier to style.</li>
</ul>
<p>The CSS is ordinary layout and colors, so it isn't covered here. You can copy it from the demo files.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/6fb5ea62-ebe4-4ab0-8ec6-6b7e87897f23.png" alt="Upload area of the PDF password protector with a Select PDF button" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-opening-the-pdf">Opening the PDF</h2>
<p>First, <code>script.js</code> takes the classes it needs from the two libraries, points PDF.js to its worker, and keeps the app's state in one object:</p>
<pre><code class="language-js">// ---------- Setup ----------
const { PDFDocument, PDFName, PDFNumber, PDFBool, PDFHexString, PDFString,
  PDFDict, PDFArray, PDFRawStream } = PDFLib;

pdfjsLib.GlobalWorkerOptions.workerSrc =
  'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

const state = {
  file: null,     // the File the user picked
  bytes: null,    // its contents as a Uint8Array
  pages: 0,
  result: null    // the protected PDF as a Uint8Array
};

const $ = (id) =&gt; document.getElementById(id);
const uploadArea = $('uploadArea');
const fileInput = $('fileInput');
const fileInfo = $('fileInfo');
const settings = $('settings');
const openPw = $('openPw');
const openPw2 = $('openPw2');
const ownerPw = $('ownerPw');
const strength = $('strength');
const protectBtn = $('protectBtn');
const statusText = $('status');
const result = $('result');
const checks = $('checks');
const fileName = $('fileName');
const downloadBtn = $('downloadBtn');
</code></pre>
<p>The user can pick a file with the button or drop it on the upload area:</p>
<pre><code class="language-js">// ---------- Opening the PDF ----------
$('selectBtn').addEventListener('click', () =&gt; fileInput.click());
fileInput.addEventListener('change', () =&gt; {
  if (fileInput.files[0]) loadFile(fileInput.files[0]);
  fileInput.value = '';
});

uploadArea.addEventListener('dragover', (e) =&gt; {
  e.preventDefault();
  uploadArea.classList.add('dragover');
});
uploadArea.addEventListener('dragleave', () =&gt; uploadArea.classList.remove('dragover'));
uploadArea.addEventListener('drop', (e) =&gt; {
  e.preventDefault();
  uploadArea.classList.remove('dragover');
  if (e.dataTransfer.files[0]) loadFile(e.dataTransfer.files[0]);
});
</code></pre>
<p>Setting <code>fileInput.value = ''</code> after reading the file lets the user pick the same file again.</p>
<p><code>loadFile</code> checks that the file is a PDF, reads it into a <code>Uint8Array</code>, and tries to load it with PDF-lib:</p>
<pre><code class="language-js">async function loadFile(file) {
  const isPdf = file.type === 'application/pdf' || /\.pdf$/i.test(file.name);
  if (!isPdf) {
    fileInfo.textContent = `${file.name} is not a PDF.`;
    return;
  }

  const bytes = new Uint8Array(await file.arrayBuffer());
  try {
    const doc = await PDFDocument.load(bytes, { updateMetadata: false });
    state.file = file;
    state.bytes = bytes;
    state.pages = doc.getPageCount();
  } catch (err) {
    fileInfo.textContent = /encrypted/i.test(err.message)
      ? `${file.name} already has a password. Unlock it first.`
      : `${file.name} could not be read. The file may be damaged.`;
    return;
  }

  fileInfo.textContent = `${file.name}: ${state.pages} page(s), ${formatSize(file.size)}`;
  settings.hidden = false;
  result.hidden = true;
  openPw.focus();
}

function formatSize(n) {
  if (n &lt; 1024) return n + ' B';
  if (n &lt; 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
  return (n / 1024 / 1024).toFixed(1) + ' MB';
}
</code></pre>
<p>Loading the file here does two jobs. It counts the pages, which you'll use later to check the result, and it catches files that already have a password: PDF-lib throws an error whose message contains "encrypted" when it sees one, so the tool can tell the user to unlock the file first.</p>
<p>The <code>updateMetadata: false</code> option is important here. By default, PDF-lib changes the file's Producer and modification date when it loads a document. You only want to add a password, not rewrite the document's details.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/30adb2ac-f245-4a7b-a32e-2416dcd7158c.png" alt="Message saying the selected PDF already has a password and must be unlocked first" style="display: block;" width="600" height="400" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/aa182706-202a-4dc5-841a-823dcd77efbb.png" alt="PDF loaded with its page count and size, and the password and permission settings shown" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-handling-the-password-fields">Handling the Password Fields</h2>
<p>Each Show button switches its input between <code>password</code> and <code>text</code>, so the user can check what they typed:</p>
<pre><code class="language-js">// ---------- Password fields ----------
document.querySelectorAll('.show-btn').forEach((btn) =&gt; {
  btn.addEventListener('click', () =&gt; {
    const input = $(btn.dataset.target);
    const show = input.type === 'password';
    input.type = show ? 'text' : 'password';
    btn.textContent = show ? 'Hide' : 'Show';
  });
});
</code></pre>
<p>While the user types, a short hint rates the password. It counts how many kinds of characters it contains (lowercase, uppercase, digits, and symbols):</p>
<pre><code class="language-js">openPw.addEventListener('input', () =&gt; {
  const pw = openPw.value;
  const kinds = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^A-Za-z0-9]/]
    .filter((re) =&gt; re.test(pw)).length;

  if (pw.length &lt; 8) {
    strength.textContent = 'Use at least 8 characters.';
    strength.className = 'hint weak';
  } else if (pw.length &gt;= 12 &amp;&amp; kinds &gt;= 3) {
    strength.textContent = 'Strong password.';
    strength.className = 'hint good';
  } else {
    strength.textContent = 'OK. A longer password with numbers and symbols is stronger.';
    strength.className = 'hint';
  }
});
</code></pre>
<p>This isn't a real strength meter, and it doesn't need to be one. Its job is to push people away from passwords like <code>1234</code>.</p>
<p>Before encrypting, <code>passwordProblem</code> returns a message if something is wrong, or an empty string if everything is fine:</p>
<pre><code class="language-js">function passwordProblem() {
  if (openPw.value.length &lt; 8) return 'The password must have at least 8 characters.';
  if (openPw.value !== openPw2.value) return 'The two passwords are different.';
  if (ownerPw.value &amp;&amp; ownerPw.value === openPw.value) {
    return 'Use a different permissions password, or leave it empty.';
  }
  return '';
}
</code></pre>
<p>The last rule is there because if both passwords are the same, the permissions are pointless: anyone who can open the file can also change them.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/46301cdb-393f-4238-b237-88d96a359bac.png" alt="Password fields with a red border and the message that the two passwords are different" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-helpers-for-bytes-and-web-crypto">Helpers for Bytes and Web Crypto</h2>
<p>Encryption works on bytes, so you need a few small helpers. <code>concat</code> joins byte arrays, <code>randomBytes</code> gets secure random bytes, and <code>toHex</code> turns bytes into a hex string for PDF-lib:</p>
<pre><code class="language-js">// ---------- Byte helpers ----------
function concat(...parts) {
  const out = new Uint8Array(parts.reduce((n, p) =&gt; n + p.length, 0));
  let offset = 0;
  for (const p of parts) {
    out.set(p, offset);
    offset += p.length;
  }
  return out;
}

const randomBytes = (n) =&gt; crypto.getRandomValues(new Uint8Array(n));

function toHex(bytes) {
  return Array.from(bytes, (b) =&gt; b.toString(16).padStart(2, '0')).join('');
}

// PDF 2.0 passwords are UTF-8, normalized, and at most 127 bytes long
function passwordBytes(text) {
  return new TextEncoder().encode(text.normalize('NFKC')).slice(0, 127);
}
</code></pre>
<p><code>passwordBytes</code> prepares a password the way PDF 2.0 expects: as UTF-8, at most 127 bytes long. The <code>normalize('NFKC')</code> call makes sure that characters which look the same are stored the same way, so for example <code>é</code> typed on two different keyboards gives the same bytes. The specification uses a slightly stricter process called SASLprep, but NFKC covers the cases people actually come across.</p>
<p>Next come the Web Crypto helpers:</p>
<pre><code class="language-js">// ---------- Web Crypto helpers ----------
async function digest(algorithm, data) {
  return new Uint8Array(await crypto.subtle.digest(algorithm, data));
}

// AES-CBC with PKCS#7 padding (what PDF uses for strings and streams)
async function aesEncrypt(keyBytes, iv, data) {
  const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-CBC', false, ['encrypt']);
  return new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-CBC', iv }, key, data));
}

// AES-CBC without padding: the input is already a multiple of 16 bytes,
// so we keep the first data.length bytes and drop the extra padding block
async function aesEncryptNoPad(keyBytes, iv, data) {
  return (await aesEncrypt(keyBytes, iv, data)).slice(0, data.length);
}
</code></pre>
<p>Web Crypto's AES-CBC always adds PKCS#7 padding. PDF needs padding for strings and streams, so <code>aesEncrypt</code> is perfect for them. But a few values in the encryption dictionary must be encrypted <em>without</em> padding. Their input is always a multiple of 16 bytes, so the first <code>data.length</code> bytes of the output are exactly what you need, and <code>aesEncryptNoPad</code> simply drops the extra padding block.</p>
<h2 id="heading-hashing-the-password-the-pdf-20-way">Hashing the Password the PDF 2.0 Way</h2>
<p>AES-256 PDFs don't use a plain SHA-256 of the password. They use a slower hash (Algorithm 2.B in ISO 32000-2) that makes guessing passwords expensive:</p>
<pre><code class="language-js">// ---------- The PDF 2.0 password hash ----------
// ISO 32000-2, Algorithm 2.B: SHA-256, then at least 64 rounds of
// AES-128 + SHA-256/384/512 to make guessing passwords slow
async function hashPassword(password, salt, userKey) {
  let k = await digest('SHA-256', concat(password, salt, userKey));
  let e = new Uint8Array([0]);
  let round = 0;

  while (round &lt; 64 || e[e.length - 1] &gt; round - 32) {
    const block = concat(password, k, userKey);
    const k1 = new Uint8Array(block.length * 64);
    for (let i = 0; i &lt; 64; i++) k1.set(block, i * block.length);

    e = await aesEncryptNoPad(k.slice(0, 16), k.slice(16, 32), k1);

    let sum = 0;
    for (let i = 0; i &lt; 16; i++) sum += e[i];
    const hash = ['SHA-256', 'SHA-384', 'SHA-512'][sum % 3];
    k = await digest(hash, e);
    round++;
  }
  return k.slice(0, 32);
}
</code></pre>
<p>Here's what happens:</p>
<ol>
<li>Start with a SHA-256 hash of the password, a salt, and (for the owner password) the 48-byte <code>U</code> value.</li>
<li>Repeat the password, the current hash, and the extra data 64 times, and encrypt that block with AES-128. The key and IV come from the current hash.</li>
<li>Add up the first 16 bytes of the result. The remainder after dividing by 3 decides whether the next hash is SHA-256, SHA-384, or SHA-512.</li>
<li>Do this at least 64 times, then keep going until the last byte of the encrypted block is no bigger than the round number minus 32.</li>
<li>The first 32 bytes of the final hash are the result.</li>
</ol>
<p>Because the number of rounds and the hash function depend on the data, an attacker can't easily speed this up with special hardware. A browser still finishes it in a few milliseconds.</p>
<h2 id="heading-turning-permissions-into-a-number">Turning Permissions into a Number</h2>
<p>The permissions are stored in <code>/P</code> as a 32-bit number, where each bit allows one action:</p>
<pre><code class="language-js">// ---------- Permissions ----------
// Bit positions from the PDF specification (bit 1 is the lowest bit)
const PERM = {
  print: 1 &lt;&lt; 2,          // bit 3
  modify: 1 &lt;&lt; 3,         // bit 4
  copy: 1 &lt;&lt; 4,           // bit 5
  annotate: 1 &lt;&lt; 5,       // bit 6
  fillForms: 1 &lt;&lt; 8,      // bit 9
  accessibility: 1 &lt;&lt; 9,  // bit 10
  assemble: 1 &lt;&lt; 10,      // bit 11
  printHigh: 1 &lt;&lt; 11      // bit 12
};

function permissionFlags({ print, copy, edit }) {
  let p = 0xFFFFF0C0;                    // reserved bits that must be 1
  p |= PERM.accessibility;               // always allow screen readers
  if (print) p |= PERM.print | PERM.printHigh;
  if (copy) p |= PERM.copy;
  if (edit) p |= PERM.modify | PERM.annotate | PERM.fillForms | PERM.assemble;
  return p | 0;                          // as a signed 32-bit number
}
</code></pre>
<p>The starting value <code>0xFFFFF0C0</code> sets the bits that the specification says must always be 1. The function then turns on bit 10 (text extraction for accessibility) so screen readers keep working, and adds the bits for each option the user ticked:</p>
<table>
<thead>
<tr>
<th>Option in the tool</th>
<th>Bits turned on</th>
</tr>
</thead>
<tbody><tr>
<td>Print</td>
<td>3 (print) and 12 (high-quality print)</td>
</tr>
<tr>
<td>Copy text and images</td>
<td>5</td>
</tr>
<tr>
<td>Edit, comment, and fill forms</td>
<td>4, 6, 9 and 11</td>
</tr>
</tbody></table>
<p>The final <code>p | 0</code> converts the number to a signed 32-bit integer. With high bits set, it's negative, and that's normal: most PDFs show something like <code>/P -1324</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/d82f0a23-bfde-43f2-9457-bad333438ac0.png" alt="Open password marked as strong, with Print allowed and copying and editing turned off" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-building-the-encryption-keys">Building the Encryption Keys</h2>
<p>Now you can build the values that go into the encryption dictionary:</p>
<pre><code class="language-js">// ---------- Building the encryption dictionary values ----------
async function makeKeys(userText, ownerText, p) {
  const fileKey = randomBytes(32);       // the key that encrypts the document
  const user = passwordBytes(userText);
  const owner = passwordBytes(ownerText);
  const none = new Uint8Array(0);
  const zeroIv = new Uint8Array(16);

  // U and UE: check the open password and unlock the file key with it
  const uValidation = randomBytes(8);
  const uKeySalt = randomBytes(8);
  const U = concat(await hashPassword(user, uValidation, none), uValidation, uKeySalt);
  const UE = await aesEncryptNoPad(await hashPassword(user, uKeySalt, none), zeroIv, fileKey);

  // O and OE: the same for the permissions password (they also depend on U)
  const oValidation = randomBytes(8);
  const oKeySalt = randomBytes(8);
  const O = concat(await hashPassword(owner, oValidation, U), oValidation, oKeySalt);
  const OE = await aesEncryptNoPad(await hashPassword(owner, oKeySalt, U), zeroIv, fileKey);

  // Perms: the permissions, encrypted with the file key so they can't be edited
  const perms = new Uint8Array(16);
  new DataView(perms.buffer).setInt32(0, p, true);   // little-endian
  perms.set([0xFF, 0xFF, 0xFF, 0xFF], 4);
  perms.set([0x54, 0x61, 0x64, 0x62], 8);            // 'T' (encrypt metadata), 'a', 'd', 'b'
  perms.set(randomBytes(4), 12);
  const Perms = await aesEncryptNoPad(fileKey, zeroIv, perms);

  return { fileKey, U, UE, O, OE, Perms };
}
</code></pre>
<p>Let's go through them:</p>
<ul>
<li><code>fileKey</code> is 32 random bytes. It encrypts the whole document.</li>
<li><code>U</code> (48 bytes) lets a reader check the user password. It's the password hash plus two 8-byte random salts: a <em>validation salt</em> used to check the password, and a <em>key salt</em> used to unlock the key.</li>
<li><code>UE</code> is the file key, encrypted with a hash of the user password and the key salt. When someone types the right password, the reader rebuilds this hash and decrypts the file key.</li>
<li><code>O</code> and <code>OE</code> do the same for the owner password. Their hashes also include <code>U</code>, which ties the two passwords to the same file.</li>
<li><code>Perms</code> is the permission number plus a few check bytes, encrypted with the file key. A reader decrypts it and compares it with <code>/P</code>, so someone who edits <code>/P</code> in a text editor gets caught.</li>
</ul>
<p>Two rules from the specification show up here:</p>
<ul>
<li><code>UE</code>, <code>OE</code> and <code>Perms</code> are encrypted without padding and with an IV of zeros. (<code>Perms</code> is a single 16-byte block, so AES-CBC with a zero IV gives the same result as the AES-ECB mode the specification describes.)</li>
<li>The byte <code>T</code> in <code>Perms</code> means "the metadata is encrypted too", which must match <code>/EncryptMetadata true</code> in the dictionary.</li>
</ul>
<h2 id="heading-encrypting-every-string-and-stream">Encrypting Every String and Stream</h2>
<p>With the file key ready, you can encrypt the document. For AES-256, each string or stream is encrypted with the file key and a new random 16-byte IV, and the IV is stored in front of the encrypted bytes:</p>
<pre><code class="language-js">// ---------- Encrypting the objects ----------
// With AES-256 every string and stream is encrypted with the file key
// and a fresh random IV, which is stored in front of the encrypted data
async function encryptData(fileKey, data) {
  const iv = randomBytes(16);
  return concat(iv, await aesEncrypt(fileKey, iv, data));
}

async function encryptStrings(value, fileKey) {
  if (value instanceof PDFDict) {
    for (const [key, item] of value.entries()) {
      const replacement = await encryptValue(item, fileKey);
      if (replacement) value.set(key, replacement);
    }
  } else if (value instanceof PDFArray) {
    for (let i = 0; i &lt; value.size(); i++) {
      const replacement = await encryptValue(value.get(i), fileKey);
      if (replacement) value.set(i, replacement);
    }
  }
}

async function encryptValue(item, fileKey) {
  if (item instanceof PDFString || item instanceof PDFHexString) {
    return PDFHexString.of(toHex(await encryptData(fileKey, item.asBytes())));
  }
  await encryptStrings(item, fileKey);   // nested dictionaries and arrays
  return null;
}

async function encryptObjects(context, fileKey) {
  const objects = context.enumerateIndirectObjects();
  for (const [ref, object] of objects) {
    if (object instanceof PDFRawStream) {
      const type = object.dict.get(PDFName.of('Type'));
      if (type === PDFName.of('XRef')) {     // old cross-reference streams
        context.delete(ref);
        continue;
      }
      await encryptStrings(object.dict, fileKey);
      const data = await encryptData(fileKey, object.contents);
      context.assign(ref, PDFRawStream.of(object.dict, data));
    } else {
      await encryptStrings(object, fileKey);
    }
  }
}
</code></pre>
<p><code>encryptObjects</code> goes through every object in the file:</p>
<ul>
<li><strong>Streams</strong> (<code>PDFRawStream</code>): their data is replaced with the encrypted version. PDF-lib updates the <code>/Length</code> entry for you when it saves.</li>
<li><strong>Dictionaries and arrays</strong>: <code>encryptStrings</code> walks through them and replaces every string with an encrypted hex string. Nested dictionaries and arrays are handled by calling the function again.</li>
<li><strong>Cross-reference streams</strong> (<code>/Type /XRef</code>) are deleted. They describe where objects sit in the old file, PDF-lib writes a new cross-reference table anyway, and they must never be encrypted.</li>
</ul>
<p>PDF-lib has two string types: <code>PDFString</code> for literal strings like <code>(Hello)</code> and <code>PDFHexString</code> for hex strings like <code>&lt;48656C6C6F&gt;</code>. Both have an <code>asBytes()</code> method that returns the real bytes, which is what you encrypt.</p>
<p>The stream data is encrypted <em>as it is in the file</em>, which is usually already compressed. That's the correct order: a reader decrypts first, then decompresses.</p>
<h2 id="heading-writing-the-protected-pdf">Writing the Protected PDF</h2>
<p><code>protectPdf</code> puts it all together:</p>
<pre><code class="language-js">// ---------- Protecting the PDF ----------
async function protectPdf(bytes, options) {
  const doc = await PDFDocument.load(bytes, { updateMetadata: false });
  const context = doc.context;

  const p = permissionFlags(options);
  const ownerText = options.ownerPw || toHex(randomBytes(16));
  const keys = await makeKeys(options.openPw, ownerText, p);

  // 1. Encrypt every string and stream that is already in the file
  await encryptObjects(context, keys.fileKey);

  // 2. Add the encryption dictionary (it must NOT be encrypted itself)
  const hex = (b) =&gt; PDFHexString.of(toHex(b));
  const stdCF = context.obj({ AuthEvent: 'DocOpen', CFM: 'AESV3', Length: 32 });
  const encrypt = context.obj({
    Filter: 'Standard',
    V: 5,
    R: 6,
    Length: 256,
    CF: context.obj({ StdCF: stdCF }),
    StmF: 'StdCF',
    StrF: 'StdCF',
    P: PDFNumber.of(p),
    EncryptMetadata: PDFBool.True
  });
  encrypt.set(PDFName.of('U'), hex(keys.U));
  encrypt.set(PDFName.of('UE'), hex(keys.UE));
  encrypt.set(PDFName.of('O'), hex(keys.O));
  encrypt.set(PDFName.of('OE'), hex(keys.OE));
  encrypt.set(PDFName.of('Perms'), hex(keys.Perms));

  // 3. Point the trailer at it and give the file an ID
  context.trailerInfo.Encrypt = context.register(encrypt);
  const id = hex(randomBytes(16));
  context.trailerInfo.ID = context.obj([id, id]);

  // Object streams would hide objects from step 1, so write plain objects
  return doc.save({ useObjectStreams: false });
}
</code></pre>
<p>The steps are:</p>
<ol>
<li>Encrypt the existing objects: This must happen <em>before</em> you add the encryption dictionary, because the dictionary itself must stay readable.</li>
<li>Create the encryption dictionary: <code>context.obj()</code> turns plain strings into PDF names, so <code>Filter: 'Standard'</code> becomes <code>/Filter /Standard</code>. <code>V 5</code> and <code>R 6</code> mean AES-256 from PDF 2.0, and the crypt filter <code>StdCF</code> with <code>CFM AESV3</code> tells the reader to use AES-256 for both streams (<code>StmF</code>) and strings (<code>StrF</code>).</li>
<li>Update the trailer: The trailer gets an <code>/Encrypt</code> reference and a new <code>/ID</code>. PDF-lib writes <code>trailerInfo</code> into the trailer for you, and it doesn't encrypt the ID.</li>
</ol>
<p>If the user leaves the permissions password empty, the tool uses 16 random bytes as the owner password. Nobody knows it, so nobody can lift the restrictions. (If you used an empty owner password instead, any PDF program could remove them.)</p>
<p>Finally, the file is saved with <code>useObjectStreams: false</code>. An object stream packs many objects into one compressed stream. Strings inside an object stream must not be encrypted on their own, because the whole stream is encrypted. You already encrypted every string individually, so writing plain objects keeps the file correct.</p>
<p>Here's what the encryption dictionary looks like in the saved file:</p>
<pre><code class="language-text">&lt;&lt;
/Filter /Standard /V 5 /R 6 /Length 256
/CF &lt;&lt; /StdCF &lt;&lt; /AuthEvent /DocOpen /CFM /AESV3 /Length 32 &gt;&gt; &gt;&gt;
/StmF /StdCF /StrF /StdCF
/P -1324 /EncryptMetadata true
/U &lt;...48 bytes...&gt; /UE &lt;...32 bytes...&gt;
/O &lt;...48 bytes...&gt; /OE &lt;...32 bytes...&gt;
/Perms &lt;...16 bytes...&gt;
&gt;&gt;
</code></pre>
<h2 id="heading-checking-the-result-with-pdfjs">Checking the Result with PDF.js</h2>
<p>Encryption bugs are easy to make and hard to notice. A file might open in one reader and fail in another, or it might not be encrypted at all. So the tool opens its own output with PDF.js before offering the download:</p>
<pre><code class="language-js">// ---------- Checking the result with PDF.js ----------
async function verify(bytes, password) {
  const results = [];

  // 1. Without a password, PDF.js must ask for one
  try {
    const doc = await pdfjsLib.getDocument({ data: bytes.slice() }).promise;
    await doc.destroy();
    results.push([false, 'The file opened without a password']);
  } catch (err) {
    results.push([err.name === 'PasswordException', 'Asks for a password when opened']);
  }

  // 2. With the password, it must open and have every page
  try {
    const doc = await pdfjsLib.getDocument({ data: bytes.slice(), password }).promise;
    results.push([doc.numPages === state.pages, `Opens with your password (${doc.numPages} page(s))`]);
    await doc.destroy();
  } catch (err) {
    results.push([false, 'Could not open it with your password']);
  }
  return results;
}
</code></pre>
<p>There are two checks:</p>
<ol>
<li>Opening the file <strong>without</strong> a password must fail with a <code>PasswordException</code>. If it opens, the file isn't protected.</li>
<li>Opening it <strong>with</strong> the password must work, and it must have the same number of pages as the original.</li>
</ol>
<p><code>bytes.slice()</code> passes a copy, because PDF.js moves the buffer to its worker and the original array would become empty.</p>
<h2 id="heading-connecting-the-button">Connecting the Button</h2>
<p>The click handler checks the passwords, runs <code>protectPdf</code>, runs the checks, and shows the result:</p>
<pre><code class="language-js">// ---------- Running everything ----------
protectBtn.addEventListener('click', async () =&gt; {
  const problem = passwordProblem();
  openPw.setAttribute('aria-invalid', String(openPw.value.length &lt; 8));
  openPw2.setAttribute('aria-invalid', String(openPw.value !== openPw2.value));
  if (problem) {
    statusText.textContent = problem;
    statusText.className = 'status error';
    return;
  }

  protectBtn.disabled = true;
  statusText.className = 'status';
  statusText.textContent = 'Encrypting…';
  try {
    const options = {
      openPw: openPw.value,
      ownerPw: ownerPw.value,
      print: $('allowPrint').checked,
      copy: $('allowCopy').checked,
      edit: $('allowEdit').checked
    };
    state.result = await protectPdf(state.bytes, options);

    statusText.textContent = 'Checking the protected file…';
    const results = await verify(state.result, options.openPw);
    checks.innerHTML = '';
    for (const [ok, text] of results) {
      const li = document.createElement('li');
      li.textContent = (ok ? '✅ ' : '❌ ') + text;
      checks.appendChild(li);
    }
    const sizeLi = document.createElement('li');
    sizeLi.textContent = 'Size: ' + formatSize(state.result.length);
    checks.appendChild(sizeLi);

    fileName.value = state.file.name.replace(/\.pdf$/i, '') + '-protected.pdf';
    statusText.textContent = '';
    result.hidden = false;
    result.scrollIntoView({ behavior: 'smooth' });
  } catch (err) {
    console.error(err);
    statusText.textContent = 'Something went wrong: ' + err.message;
    statusText.className = 'status error';
  } finally {
    protectBtn.disabled = false;
  }
});
</code></pre>
<p>The button is disabled while the work runs, so a double click doesn't start two encryptions. The <code>finally</code> block turns it back on, even if something fails.</p>
<h2 id="heading-renaming-and-downloading">Renaming and Downloading</h2>
<p>The result panel suggests a name such as <code>report-protected.pdf</code>. When the user clicks Download PDF, the name is cleaned and the file is saved:</p>
<pre><code class="language-js">// ---------- Downloading ----------
downloadBtn.addEventListener('click', () =&gt; {
  let name = fileName.value.trim().replace(/[\\/:*?"&lt;&gt;|]+/g, '-') || 'protected.pdf';
  if (!/\.pdf$/i.test(name)) name += '.pdf';

  const blob = new Blob([state.result], { type: 'application/pdf' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = name;
  a.click();
  setTimeout(() =&gt; URL.revokeObjectURL(url), 60000);
});
</code></pre>
<p>The regular expression replaces characters that Windows doesn't allow in file names. The object URL is released after a minute, which gives the browser plenty of time to start the download.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/a0e84770-9203-4b41-a7b2-d981ca9a5110.png" alt="Result panel showing that the PDF asks for a password and opens with it, plus file name and Download button" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-testing-the-file-outside-the-browser">Testing the File Outside the Browser</h2>
<p>A PDF that only opens in your own tool isn't very useful. So you'll want to test the output in other software too.</p>
<p><a href="https://qpdf.readthedocs.io/">qpdf</a> is a free command-line tool that reads encrypted PDFs strictly. These commands check the file and show its encryption settings:</p>
<pre><code class="language-bash"># Should say: "invalid password"
qpdf --check report-protected.pdf

# Should say: "No syntax or stream encoding errors found"
qpdf --check --password='your password' report-protected.pdf

# Shows R = 6, AESv3 and each permission
qpdf --show-encryption --password='your password' report-protected.pdf
</code></pre>
<p>For the version in this article, <code>qpdf --show-encryption</code> prints:</p>
<pre><code class="language-text">R = 6
P = -1324
User password = Correct-Horse-42
Supplied password is user password
extract for accessibility: allowed
extract for any purpose: allowed
print low resolution: allowed
print high resolution: allowed
modify document assembly: not allowed
modify forms: not allowed
modify annotations: not allowed
modify other: not allowed
modify anything: not allowed
stream encryption method: AESv3
string encryption method: AESv3
file encryption method: AESv3
</code></pre>
<p>Also open the file in your browser's PDF viewer and in Adobe Acrobat Reader. Both should ask for the password, and Acrobat's Document Properties &gt; Security tab should show the restrictions you chose.</p>
<h2 id="heading-demo-how-the-protect-pdf-tool-works">Demo: How the Protect PDF Tool Works</h2>
<p>Here's the workflow in the full tool on All In One Tools.</p>
<h3 id="heading-step-1-add-your-pdf">Step 1: Add Your PDF</h3>
<p>Drop a PDF on the page or click Select PDF. The pages appear as previews, so you can check that it's the right file before you protect it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/584913da-37cf-4a9e-ba97-aeed28b65e09.png" alt="Uploaded PDF with its file name, size and a large preview of the page" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-2-choose-the-passwords-and-limits">Step 2: Choose the Passwords and Limits</h3>
<p>Type the open password twice. If you want to limit printing, copying or editing, turn on the limits and set a separate permissions password. AES-256 is selected by default.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/ebb38969-3a0b-40ca-a380-d2959e0827fd.png" alt="Password settings with AES-256 selected, open password, permissions password and printing and copying limits" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-3-check-and-download">Step 3: Check and Download</h3>
<p>The tool opens the protected file in the browser, checks that it asks for a password, accepts yours and refuses a wrong one, and then shows a preview. Rename the file if you like and click Download PDF.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/dc2a1ce7-bbdc-45cd-9c30-865adcecd01e.png" alt="Protected PDF preview with the in-browser checks passed and a Download PDF button" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-performance-tips">Performance Tips</h2>
<p>There are a few things you can do to make sure the tool performs well.</p>
<p>First, process objects one at a time. The code <code>await</code>s each encryption in turn. That keeps memory use low, because only one stream is copied at a time. For files with thousands of small objects you can encrypt in batches of, say, 50 with <code>Promise.all</code> to go faster.</p>
<p>Second, expect the file to grow a little. Each string and stream gains a 16-byte IV and up to 16 bytes of padding, and saving without object streams makes the cross-reference table bigger. A 4 KB file might become 8 KB, while a 5 MB file grows by only a few kilobytes.</p>
<p>Next, don't encrypt twice for the check. The tool verifies the exact bytes it's going to download. Don't run <code>protectPdf</code> again for the download, or the file will get a new random key and the check will no longer apply to it.</p>
<p>Finally, release memory after big files. Call <code>doc.destroy()</code> on PDF.js documents when you're done, as <code>verify</code> does. Otherwise the worker keeps the parsed file in memory.</p>
<h2 id="heading-common-mistakes">Common Mistakes</h2>
<p>There are also a few things to avoid when you're building this tool.</p>
<p>First, don't open the page over plain <code>http://</code>. <code>crypto.subtle</code> only exists in secure contexts. On <code>http://example.com</code> or a <code>file://</code> path, the code fails with "Cannot read properties of undefined (reading 'digest')". Use <code>https://</code> or <code>localhost</code>.</p>
<p>Don't use <code>Math.random()</code> for keys or salts. It isn't designed for security, and its output can be predicted. Always use <code>crypto.getRandomValues()</code>.</p>
<p>You also shouldn't encrypt the encryption dictionary. If the <code>/U</code>, <code>/O</code> or <code>/Perms</code> strings get encrypted, no reader can check a password. Encrypt the document first, then add the dictionary.</p>
<p>Avoid saving with object streams. PDF-lib saves with object streams by default. With encryption, strings inside them would be encrypted twice. Pass <code>useObjectStreams: false</code>.</p>
<p>Also, don't forget <code>slice()</code> when passing bytes to PDF.js. PDF.js transfers the buffer to its worker. Afterwards your original <code>Uint8Array</code> is empty, and the download is a 0-byte file.</p>
<p>Don't treat permissions as security. Restricting printing and copying is useful for honest readers, but it isn't protection. If the content must stay private, the open password is what matters.</p>
<p>Don't protect a digitally signed PDF. Encrypting changes every byte that the signature covers, so the signature becomes invalid. Add the password first, then sign the protected file.</p>
<p>And finally, make sure you and your users don't lose the password. With AES-256 there's no back door and no "forgot password" button. Tell your users to store the password somewhere safe.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you built a browser-based tool that adds a password to a PDF with AES-256 encryption.</p>
<p>You learned how PDF encryption is organized, how to hash a password with the PDF 2.0 algorithm, how to build the <code>U</code>, <code>UE</code>, <code>O</code>, <code>OE</code> and <code>Perms</code> values with the Web Crypto API, how to encrypt every string and stream with PDF-lib, and how to check the result with PDF.js and qpdf.</p>
<p>All of it runs in the browser, so the document stays on the user's device.</p>
<p>You can try the full version of this tool, with page previews, AES-128 and RC4 options for very old readers, low-resolution-only printing, and more detailed permission choices at <a href="https://allinonetools.net/protect-pdf/">Protect PDF</a>.</p>
<p>If you want to extend your version, here are some ideas:</p>
<ul>
<li>Add an Unlock tool that removes the password when the user knows it</li>
<li>Let users choose "print in low resolution only" (bit 3 without bit 12)</li>
<li>Protect several PDFs with the same password in one go</li>
<li>Show a warning when the PDF has a digital signature</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Browser-Based Image Storyboard to PDF Tool Using JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Before anyone films a video, shoots an ad or draws the final pages of a comic, someone usually sketches the plan as a storyboard: one picture per shot, in order, with a short note about what happens a ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-image-storyboard-to-pdf-tool-javascript/</link>
                <guid isPermaLink="false">6af6ea1b6758a8ccb76659d6</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pdf ]]>
                    </category>
                
                    <category>
                        <![CDATA[ canvas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ indexeddb ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavin Sheth ]]>
                </dc:creator>
                <pubDate>Fri, 13 Nov 2026 10:44:43 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5fc16e412cae9c5b190b6cdd/eb2e1525-11db-47ef-a27c-b0672184efe8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Before anyone films a video, shoots an ad or draws the final pages of a comic, someone usually sketches the plan as a storyboard: one picture per shot, in order, with a short note about what happens and how long it lasts.</p>
<p>Most people already have those pictures. They are phone photos, screenshots, rough sketches or AI-generated frames sitting in a folder. What they don't have is a quick way to turn that folder into clean, numbered sheets they can print or send to a client.</p>
<p>In this tutorial, you'll build a browser-based tool that does exactly that. You'll add a set of images, give each one a title, a description and a duration, choose a layout, preview the sheets, and download a print-ready PDF.</p>
<p>Everything runs in the browser. The images are never uploaded to a server, which matters when the frames are unreleased product shots or client work.</p>
<p>Along the way, you'll learn how to fix sideways phone photos, sort files the way people expect, lay out a page in PDF points, wrap text on a canvas, save a draft with IndexedDB, and build a PDF that keeps photos sharp without making the file huge.</p>
<p>I built this tool for AllInOneTools, where it runs as the Image Storyboard to PDF tool. This article walks through a simplified version that you can build in three files.</p>
<h2 id="heading-what-well-cover">What We'll Cover</h2>
<ul>
<li><a href="#heading-what-this-image-storyboard-tool-does-and-how-it-works">What This Image Storyboard Tool Does and How It Works</a></li>
<li><a href="#heading-project-setup">Project Setup</a></li>
<li><a href="#heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</a></li>
<li><a href="#heading-creating-the-html-layout">Creating the HTML Layout</a></li>
<li><a href="#heading-adding-and-loading-images">Adding and Loading Images</a></li>
<li><a href="#heading-managing-the-frames">Managing the Frames</a></li>
<li><a href="#heading-building-the-board-settings">Building the Board Settings</a></li>
<li><a href="#heading-laying-out-a-storyboard-sheet">Laying Out a Storyboard Sheet</a></li>
<li><a href="#heading-drawing-a-sheet-on-the-canvas">Drawing a Sheet on the Canvas</a></li>
<li><a href="#heading-previewing-the-sheets">Previewing the Sheets</a></li>
<li><a href="#heading-saving-a-draft-with-indexeddb">Saving a Draft with IndexedDB</a></li>
<li><a href="#heading-generating-the-pdf-with-pdf-lib">Generating the PDF with PDF-lib</a></li>
<li><a href="#heading-renaming-and-downloading">Renaming and Downloading</a></li>
<li><a href="#heading-demo-how-the-image-storyboard-tool-works">Demo: How the Image Storyboard Tool Works</a></li>
<li><a href="#heading-performance-tips">Performance Tips</a></li>
<li><a href="#heading-common-mistakes">Common Mistakes</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-this-image-storyboard-tool-does-and-how-it-works">What This Image Storyboard Tool Does and How It Works</h2>
<p>The tool takes a list of images and turns them into storyboard sheets. Each image becomes a <strong>frame</strong> with:</p>
<ul>
<li>a label, such as <code>Shot 1</code> or <code>Scene 1</code></li>
<li>an optional title</li>
<li>a description of what happens</li>
<li>an optional duration in seconds</li>
</ul>
<p>The frames are placed on sheets in one of four layouts:</p>
<ul>
<li><strong>One frame per page</strong>, for presenting each shot large</li>
<li><strong>Grid</strong>, for seeing the whole sequence at a glance</li>
<li><strong>Panels with notes</strong>, with ruled lines for handwritten notes on set</li>
<li><strong>Film strip</strong>, with sprocket holes for a classic look</li>
</ul>
<p>Each sheet has a title, the total running time and a sheet number at the top.</p>
<p>Here's the flow from start to finish:</p>
<pre><code class="language-text">Images → frames (title, description, duration)
       → layout (where each box goes, in PDF points)
       → canvas (labels, text, lines)
       → PDF (photos as JPEG + one text layer per sheet)
       → download
</code></pre>
<h3 id="heading-why-the-text-is-drawn-on-a-canvas">Why the Text Is Drawn on a Canvas</h3>
<p>PDF-lib can write real text into a PDF, but only with a font file you embed. The standard PDF fonts only cover basic Latin characters, so a description in Hindi, Gujarati, Arabic or Japanese would fail.</p>
<p>A canvas, on the other hand, can draw any text the device can show, using the fonts the device already has. So this tool draws all the text on a canvas at 300 dpi and puts that canvas into the PDF as an image.</p>
<p>The trade-off is that the text in the PDF isn't selectable or searchable. For a storyboard, which is mostly printed and looked at, that's usually fine. If you need searchable text, you'd embed a font with PDF-lib's <code>fontkit</code> support instead.</p>
<h2 id="heading-project-setup">Project Setup</h2>
<p>You need only three files:</p>
<pre><code class="language-text">image-storyboard/
├── index.html
├── style.css
└── script.js
</code></pre>
<p>Open <code>index.html</code> through a local server (for example, the Live Server extension in VS Code) rather than as a <code>file://</code> page, so that IndexedDB and downloads behave the same way they will on a real site.</p>
<h2 id="heading-libraries-and-browser-apis-used">Libraries and Browser APIs Used</h2>
<p>This project uses one library and a few built-in browser APIs:</p>
<ul>
<li><strong>PDF-lib</strong> creates the PDF, embeds the JPEG and PNG images, and saves the file.</li>
<li><strong>Canvas API</strong> draws the sheets for the preview and the text layer of the PDF.</li>
<li><code>createImageBitmap</code> decodes images and applies the rotation stored in phone photos.</li>
<li><strong>IndexedDB</strong> keeps a draft in the browser so the work survives a page reload.</li>
</ul>
<p>You don't need PDF.js here, because there's no PDF to read. Everything starts from images.</p>
<p>Add PDF-lib with a pinned version at the end of the <code>body</code>, before your own script:</p>
<pre><code class="language-html">&lt;script src="https://unpkg.com/pdf-lib@1.17.1/dist/pdf-lib.min.js"&gt;&lt;/script&gt;
&lt;script src="script.js"&gt;&lt;/script&gt;
</code></pre>
<p>Pinning the version means a future release of the library can't break your tool without you knowing.</p>
<h2 id="heading-creating-the-html-layout">Creating the HTML Layout</h2>
<p>The page has four parts:</p>
<ol>
<li>An upload area with a file input</li>
<li>A bar that offers to restore a saved draft</li>
<li>A frames panel with one card per image</li>
<li>A settings panel and a preview panel</li>
</ol>
<p>Here's the upload area and the draft bar:</p>
<pre><code class="language-html">&lt;!-- 1. Upload --&gt;
&lt;section id="uploadArea" class="upload-area"&gt;
  &lt;p&gt;Drop images here or&lt;/p&gt;
  &lt;button type="button" id="selectBtn"&gt;Select images&lt;/button&gt;
  &lt;input type="file" id="fileInput" accept="image/jpeg,image/png,image/webp,image/gif" multiple hidden&gt;
  &lt;p id="statusText" class="status" aria-live="polite"&gt;&lt;/p&gt;
&lt;/section&gt;

&lt;div id="draftBar" class="draft-bar" hidden&gt;
  &lt;span id="draftText"&gt;&lt;/span&gt;
  &lt;button type="button" id="restoreBtn"&gt;Restore&lt;/button&gt;
  &lt;button type="button" id="discardBtn"&gt;Discard&lt;/button&gt;
&lt;/div&gt;
</code></pre>
<p>The file input only accepts the formats every browser can decode: JPEG, PNG, WebP and GIF.</p>
<p>The workspace holds the three panels:</p>
<pre><code class="language-html">&lt;!-- 2. Workspace --&gt;
&lt;section id="workspace" class="workspace" hidden&gt;
  &lt;div class="frames-panel"&gt;
    &lt;div class="panel-head"&gt;
      &lt;h2&gt;Frames&lt;/h2&gt;
      &lt;span id="totalTime"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;label&gt;Storyboard title
      &lt;input type="text" id="boardTitle" placeholder="My video"&gt;
    &lt;/label&gt;
    &lt;ol id="frameList" class="frame-list"&gt;&lt;/ol&gt;
    &lt;button type="button" id="undoBtn" hidden&gt;Undo delete&lt;/button&gt;
    &lt;button type="button" id="addMoreBtn"&gt;Add more images&lt;/button&gt;
  &lt;/div&gt;
</code></pre>
<p>The settings panel is a list of <code>select</code> and <code>number</code> inputs. Each one has an <code>id</code> that matches a key in the settings object you'll create in JavaScript:</p>
<pre><code class="language-html">&lt;div class="settings-panel"&gt;
  &lt;h2&gt;Board settings&lt;/h2&gt;
  &lt;label&gt;Layout
    &lt;select id="layout"&gt;
      &lt;option value="page"&gt;One frame per page&lt;/option&gt;
      &lt;option value="grid" selected&gt;Grid&lt;/option&gt;
      &lt;option value="notes"&gt;Panels with notes&lt;/option&gt;
      &lt;option value="strip"&gt;Film strip&lt;/option&gt;
    &lt;/select&gt;
  &lt;/label&gt;
  &lt;label&gt;Columns &lt;input type="number" id="cols" min="1" max="6" value="3"&gt;&lt;/label&gt;
  &lt;label&gt;Rows &lt;input type="number" id="rows" min="1" max="6" value="2"&gt;&lt;/label&gt;
  &lt;!-- Paper, Orientation, Frame label, Font, Text size and
       Description lines follow the same pattern --&gt;
&lt;/div&gt;
</code></pre>
<p>The preview panel has the canvas, the sheet navigation and the download controls:</p>
<pre><code class="language-html">&lt;div class="preview-panel"&gt;
  &lt;h2&gt;Preview&lt;/h2&gt;
  &lt;canvas id="previewCanvas"&gt;&lt;/canvas&gt;
  &lt;div class="pager"&gt;
    &lt;button type="button" id="prevBtn"&gt;Previous&lt;/button&gt;
    &lt;span id="sheetInfo"&gt;&lt;/span&gt;
    &lt;button type="button" id="nextBtn"&gt;Next&lt;/button&gt;
  &lt;/div&gt;

  &lt;label&gt;File name &lt;input type="text" id="fileName" value="storyboard"&gt;&lt;/label&gt;
  &lt;label&gt;Image quality
    &lt;select id="quality"&gt;
      &lt;option value="300"&gt;Print, 300 dpi&lt;/option&gt;
      &lt;option value="150"&gt;Smaller file, 150 dpi&lt;/option&gt;
    &lt;/select&gt;
  &lt;/label&gt;
  &lt;button type="button" id="downloadBtn" class="primary"&gt;Download PDF&lt;/button&gt;
  &lt;button type="button" id="resetBtn"&gt;Start over&lt;/button&gt;
  &lt;p id="resultText" class="status" aria-live="polite"&gt;&lt;/p&gt;
&lt;/div&gt;
</code></pre>
<p>In <code>style.css</code>, add one rule that's easy to forget:</p>
<pre><code class="language-css">[hidden] { display: none !important; }
</code></pre>
<p>The workspace uses <code>display: grid</code> and the draft bar uses <code>display: flex</code>. Those rules are more specific than the browser's default style for the <code>hidden</code> attribute, so without this line, hidden elements would still show.</p>
<h3 id="heading-selecting-the-main-elements">Selecting the Main Elements</h3>
<p>At the top of <code>script.js</code>, set up the constants, the state and the element references:</p>
<pre><code class="language-javascript">// ---------- Constants ----------
const PAPERS = {
  a4: [595.28, 841.89],
  letter: [612, 792],
  a3: [841.89, 1190.55],
  slide: [405, 720],
};
const FONTS = {
  sans: "Arial, Helvetica, 'Noto Sans', sans-serif",
  serif: "Georgia, 'Times New Roman', 'Noto Serif', serif",
  mono: "'Courier New', Courier, monospace",
};
const THUMB_SIZE = 1000;
const ACCEPTED = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];

// ---------- State ----------
const state = {
  frames: [],
  title: '',
  sheet: 0,
  nextId: 1,
  lastDeleted: null,
  opts: {
    layout: 'grid', cols: 3, rows: 2, paper: 'a4', orient: 'landscape',
    label: 'shot', font: 'sans', textSize: 'm', lines: 3,
  },
};

// ---------- Elements ----------
const $ = (id) =&gt; document.getElementById(id);
const els = {
  uploadArea: $('uploadArea'), fileInput: $('fileInput'), selectBtn: $('selectBtn'),
  statusText: $('statusText'), workspace: $('workspace'), frameList: $('frameList'),
  totalTime: $('totalTime'), boardTitle: $('boardTitle'), undoBtn: $('undoBtn'),
  addMoreBtn: $('addMoreBtn'), canvas: $('previewCanvas'), prevBtn: $('prevBtn'),
  nextBtn: $('nextBtn'), sheetInfo: $('sheetInfo'), fileName: $('fileName'),
  quality: $('quality'), downloadBtn: $('downloadBtn'), resetBtn: $('resetBtn'),
  resultText: $('resultText'), draftBar: $('draftBar'), draftText: $('draftText'),
  restoreBtn: $('restoreBtn'), discardBtn: $('discardBtn'),
};
const SETTING_IDS = ['layout', 'cols', 'rows', 'paper', 'orient', 'label', 'font', 'textSize', 'lines'];
</code></pre>
<p>The <code>state</code> object is the single source of truth. The frame list, the preview and the PDF are all built from it, which keeps them in sync.</p>
<p>The paper sizes are in <strong>PDF points</strong>. One point is 1/72 of an inch, so an A4 page is 595.28 × 841.89 points. You'll do all layout math in points and only convert to pixels when drawing.</p>
<h2 id="heading-adding-and-loading-images">Adding and Loading Images</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/c8b91f4a-2a88-490c-b52e-fd9cb215e46d.png" alt="c8b91f4a-2a88-490c-b52e-fd9cb215e46d" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-opening-files-from-the-button-or-by-dropping-them">Opening Files from the Button or by Dropping Them</h3>
<p>The "Select images" button opens the hidden file input, and dropping files anywhere on the page adds them too:</p>
<pre><code class="language-javascript">// ---------- Upload area ----------
els.selectBtn.addEventListener('click', () =&gt; els.fileInput.click());
els.addMoreBtn.addEventListener('click', () =&gt; els.fileInput.click());
els.fileInput.addEventListener('change', () =&gt; {
  addFiles(els.fileInput.files);
  els.fileInput.value = '';
});

['dragenter', 'dragover'].forEach((type) =&gt; {
  document.addEventListener(type, (e) =&gt; {
    if (!e.dataTransfer.types.includes('Files')) return;
    e.preventDefault();
    els.uploadArea.classList.add('dragover');
  });
});
['dragleave', 'drop'].forEach((type) =&gt; {
  document.addEventListener(type, () =&gt; els.uploadArea.classList.remove('dragover'));
});
document.addEventListener('drop', (e) =&gt; {
  if (!e.dataTransfer.files.length) return;
  e.preventDefault();
  addFiles(e.dataTransfer.files);
});

function showWorkspace() {
  els.uploadArea.hidden = true;
  els.draftBar.hidden = true;
  els.workspace.hidden = false;
}
</code></pre>
<p>Resetting <code>fileInput.value</code> after each pick lets the user choose the same file again later. The <code>dataTransfer.types.includes('Files')</code> check makes sure the drop highlight only appears for files, not for frames being dragged inside the list.</p>
<h3 id="heading-fixing-phone-photo-rotation">Fixing Phone Photo Rotation</h3>
<p>Phones don't rotate the pixels when you hold them sideways. They save the image in the sensor's orientation and add an EXIF tag that says "rotate this 90° when you show it."</p>
<p>If you draw such a photo on a canvas with an <code>img</code> element in some browsers, or read its width and height before the rotation is applied, the frame comes out sideways or with the wrong shape.</p>
<p><code>createImageBitmap</code> with <code>imageOrientation: 'from-image'</code> asks the browser to apply the EXIF rotation while decoding:</p>
<pre><code class="language-javascript">// ---------- Loading images ----------
// Phone photos store their rotation in EXIF. imageOrientation: 'from-image'
// asks the browser to apply it, so the picture comes out the right way up.
function decodeImage(blob) {
  if ('createImageBitmap' in window) {
    return createImageBitmap(blob, { imageOrientation: 'from-image' })
      .catch(() =&gt; loadWithImgTag(blob));
  }
  return loadWithImgTag(blob);
}

function loadWithImgTag(blob) {
  return new Promise((resolve, reject) =&gt; {
    const url = URL.createObjectURL(blob);
    const img = new Image();
    img.onload = () =&gt; { URL.revokeObjectURL(url); resolve(img); };
    img.onerror = () =&gt; { URL.revokeObjectURL(url); reject(new Error('decode')); };
    img.src = url;
  });
}

function canvasToBlob(canvas, type, quality) {
  return new Promise((resolve, reject) =&gt; {
    canvas.toBlob((b) =&gt; (b ? resolve(b) : reject(new Error('encode'))), type, quality);
  });
}
</code></pre>
<p>If <code>createImageBitmap</code> isn't available or fails, the code falls back to a normal <code>img</code> element. Modern browsers apply EXIF rotation to <code>img</code> elements by default too.</p>
<p><code>canvasToBlob</code> wraps the callback-based <code>canvas.toBlob()</code> in a Promise, so you can use it with <code>await</code>.</p>
<h3 id="heading-making-a-frame-object-with-a-thumbnail">Making a Frame Object with a Thumbnail</h3>
<p>A phone photo can be 4000 × 3000 pixels or more. Drawing dozens of those every time the user types a letter would make the preview slow.</p>
<p>So each frame keeps the original file for the PDF, plus a small JPEG copy (at most 1000 pixels on its longest side) for the frame list and the preview:</p>
<pre><code class="language-javascript">async function makeFrame(file) {
  const pic = await decodeImage(file);
  const w = pic.naturalWidth || pic.width;
  const h = pic.naturalHeight || pic.height;

  // A small copy for the frame list and the preview
  const scale = Math.min(1, THUMB_SIZE / Math.max(w, h));
  const c = document.createElement('canvas');
  c.width = Math.round(w * scale);
  c.height = Math.round(h * scale);
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.drawImage(pic, 0, 0, c.width, c.height);
  if (pic.close) pic.close();

  const thumb = await canvasToBlob(c, 'image/jpeg', 0.86);
  return {
    id: 'f' + state.nextId++,
    blob: file, name: file.name, w, h,
    thumb, thumbUrl: URL.createObjectURL(thumb), thumbPic: null,
    title: '', desc: '', dur: '',
  };
}
</code></pre>
<p>Notice that <code>w</code> and <code>h</code> are read after decoding, so they're the size <strong>after</strong> rotation. A portrait phone photo gets a portrait frame.</p>
<p>The white fill before drawing matters for PNG images with transparency. JPEG has no transparency, so transparent areas would otherwise turn black.</p>
<h3 id="heading-sorting-by-file-name">Sorting by File Name</h3>
<p>People name their files <code>shot-1.jpg</code>, <code>shot-2.jpg</code> … <code>shot-10.jpg</code>. A normal string sort puts <code>shot-10</code> before <code>shot-2</code>, because it compares the character <code>1</code> with <code>2</code>.</p>
<p><code>localeCompare</code> with the <code>numeric</code> option compares the numbers inside the names as numbers:</p>
<pre><code class="language-javascript">// "shot-2.jpg" before "shot-10.jpg"
function naturalCompare(a, b) {
  return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
}
</code></pre>
<h3 id="heading-adding-the-files">Adding the Files</h3>
<p><code>addFiles</code> filters out unsupported files, sorts the rest, turns each into a frame and reports anything it skipped:</p>
<pre><code class="language-javascript">async function addFiles(fileList) {
  const files = Array.from(fileList);
  const images = files.filter((f) =&gt; ACCEPTED.includes(f.type))
    .sort((a, b) =&gt; naturalCompare(a.name, b.name));
  const skipped = files.length - images.length;
  let failed = 0;

  for (let i = 0; i &lt; images.length; i++) {
    els.statusText.textContent = `Reading image ${i + 1} of ${images.length}...`;
    try {
      state.frames.push(await makeFrame(images[i]));
    } catch (err) {
      failed++;
    }
  }

  const notes = [];
  if (skipped) notes.push(`${skipped} file(s) skipped: not JPG, PNG, WebP or GIF`);
  if (failed) notes.push(`${failed} image(s) couldn't be read`);
  els.statusText.textContent = notes.join('. ');

  if (state.frames.length) {
    showWorkspace();
    renderFrameList();
    drawPreview();
    saveDraftSoon();
  }
}
</code></pre>
<p>The images are read one at a time, not all at once with <code>Promise.all</code>. Decoding 50 large photos in parallel can run a phone out of memory, and reading them in order also keeps the status message accurate.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/e1448353-0611-4577-9f23-fff32621dd03.png" alt="The workspace after adding images: frame cards on the left, settings in the middle, the preview on the right" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-managing-the-frames">Managing the Frames</h2>
<h3 id="heading-the-frame-card">The Frame Card</h3>
<p>Each frame gets a card with its thumbnail, a title field, a description box, a duration field and three buttons:</p>
<pre><code class="language-javascript">// ---------- Frame list ----------
function escapeHtml(s) {
  const map = { '&amp;': '&amp;amp;', '&lt;': '&amp;lt;', '&gt;': '&amp;gt;', '"': '&amp;quot;', "'": '&amp;#39;' };
  return String(s).replace(/[&amp;&lt;&gt;"']/g, (c) =&gt; map[c]);
}

function renderFrameList() {
  els.frameList.innerHTML = state.frames.map((f, i) =&gt; `
    &lt;li class="frame-card" data-id="${f.id}"&gt;
      &lt;img src="${f.thumbUrl}" alt="" draggable="true"&gt;
      &lt;div&gt;
        &lt;span class="num"&gt;${i + 1}. ${escapeHtml(f.name)}&lt;/span&gt;
        &lt;input type="text" data-field="title" placeholder="Title" value="${escapeHtml(f.title)}"&gt;
        &lt;textarea data-field="desc" placeholder="What happens"&gt;${escapeHtml(f.desc)}&lt;/textarea&gt;
        &lt;input type="number" data-field="dur" min="0" step="0.5" placeholder="Seconds" value="${f.dur}"&gt;
        &lt;div class="frame-tools"&gt;
          &lt;button type="button" data-act="up" aria-label="Move frame ${i + 1} up"&gt;Up&lt;/button&gt;
          &lt;button type="button" data-act="down" aria-label="Move frame ${i + 1} down"&gt;Down&lt;/button&gt;
          &lt;button type="button" data-act="delete" aria-label="Delete frame ${i + 1}"&gt;Delete&lt;/button&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/li&gt;`).join('');
  updateTotal();
}

function updateTotal() {
  const total = totalDuration();
  els.totalTime.textContent = `${state.frames.length} frames` + (total ? `, ${formatDuration(total)}` : '');
}

function findFrame(el) {
  const li = el.closest('[data-id]');
  return li ? state.frames.findIndex((f) =&gt; f.id === li.dataset.id) : -1;
}
</code></pre>
<p>Titles and descriptions come from the user, so they're escaped before going into the HTML. Without <code>escapeHtml</code>, a title like <code>Shot "A"</code> would break the <code>value</code> attribute.</p>
<h3 id="heading-updating-the-state-while-typing">Updating the State While Typing</h3>
<p>If you rebuilt the whole list on every key press, the text field would lose focus after each letter. Instead, one <code>input</code> listener on the list updates only the state:</p>
<pre><code class="language-javascript">els.frameList.addEventListener('input', (e) =&gt; {
  const i = findFrame(e.target);
  const field = e.target.dataset.field;
  if (i &lt; 0 || !field) return;
  state.frames[i][field] = e.target.value;
  updateTotal();
  drawPreviewSoon();
  saveDraftSoon();
});
</code></pre>
<p>This uses <strong>event delegation</strong>: one listener on the list handles every field in every card, including cards added later. The <code>data-field</code> attribute tells it which property to update.</p>
<p>The preview redraw is delayed with <code>drawPreviewSoon()</code>, which you'll write later, so it runs once when the user pauses typing rather than on every letter.</p>
<h3 id="heading-durations-and-the-total-running-time">Durations and the Total Running Time</h3>
<p>Durations are stored in seconds and shown as <code>4.5 s</code> under a minute or <code>1:10</code> from one minute up:</p>
<pre><code class="language-javascript">// ---------- Durations ----------
function formatDuration(seconds) {
  const s = Number(seconds) || 0;
  if (s &lt;= 0) return '';
  if (s &lt; 60) return `${Math.round(s * 10) / 10} s`;
  const m = Math.floor(s / 60);
  const r = Math.round(s - m * 60);
  return `${m}:${String(r).padStart(2, '0')}`;
}

function totalDuration() {
  return state.frames.reduce((sum, f) =&gt; sum + (Number(f.dur) || 0), 0);
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/da223063-25f9-41e3-bb7e-c790862be4f9.png" alt="A frame card with a title, description and duration filled" style="display: block;" width="600" height="400" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/8e63a168-7ccc-43bf-a791-55e88aed6e6a.png" alt="8e63a168-7ccc-43bf-a791-55e88aed6e6a" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-reordering-frames">Reordering Frames</h3>
<p>The Up and Down buttons, and the Delete button, are handled by one click listener:</p>
<pre><code class="language-javascript">els.frameList.addEventListener('click', (e) =&gt; {
  const btn = e.target.closest('[data-act]');
  if (!btn) return;
  const i = findFrame(btn);
  if (btn.dataset.act === 'up') moveFrame(i, i - 1);
  if (btn.dataset.act === 'down') moveFrame(i, i + 1);
  if (btn.dataset.act === 'delete') deleteFrame(i);
});

function moveFrame(from, to) {
  if (to &lt; 0 || to &gt;= state.frames.length || from === to) return;
  const [frame] = state.frames.splice(from, 1);
  state.frames.splice(to, 0, frame);
  renderFrameList();
  drawPreview();
  saveDraftSoon();
}
</code></pre>
<p><code>splice(from, 1)</code> removes the frame, and <code>splice(to, 0, frame)</code> puts it back at its new position.</p>
<p>For mouse users, dragging a thumbnail onto another card moves it there. The HTML5 drag and drop API needs <code>preventDefault()</code> in <code>dragover</code>, or the browser won't allow the drop:</p>
<pre><code class="language-javascript">// Drag a thumbnail onto another card to move it there
let dragIndex = -1;
els.frameList.addEventListener('dragstart', (e) =&gt; {
  dragIndex = findFrame(e.target);
  e.dataTransfer.effectAllowed = 'move';
  e.target.closest('li').classList.add('dragging');
});
els.frameList.addEventListener('dragover', (e) =&gt; {
  if (dragIndex &gt; -1) e.preventDefault();
});
els.frameList.addEventListener('drop', (e) =&gt; {
  if (dragIndex &lt; 0) return;
  e.preventDefault();
  e.stopPropagation();
  const to = findFrame(e.target);
  moveFrame(dragIndex, to &lt; 0 ? state.frames.length - 1 : to);
  dragIndex = -1;
});
els.frameList.addEventListener('dragend', () =&gt; {
  dragIndex = -1;
  els.frameList.querySelectorAll('.dragging').forEach((li) =&gt; li.classList.remove('dragging'));
});
</code></pre>
<p><code>stopPropagation()</code> in the <code>drop</code> handler stops the document-level drop handler from treating the move as a new file drop.</p>
<p>Keep the Up and Down buttons even with drag and drop. Drag and drop doesn't work with a keyboard, and it's awkward on touch screens.</p>
<h3 id="heading-deleting-a-frame-with-undo">Deleting a Frame with Undo</h3>
<p>Deleting a frame that has a long description typed into it is painful if it was a mistake. So the tool keeps the last deleted frame and its position:</p>
<pre><code class="language-javascript">function deleteFrame(i) {
  const [frame] = state.frames.splice(i, 1);
  state.lastDeleted = { frame, index: i };
  els.undoBtn.hidden = false;
  renderFrameList();
  drawPreview();
  saveDraftSoon();
}

els.undoBtn.addEventListener('click', () =&gt; {
  if (!state.lastDeleted) return;
  const { frame, index } = state.lastDeleted;
  state.frames.splice(Math.min(index, state.frames.length), 0, frame);
  state.lastDeleted = null;
  els.undoBtn.hidden = true;
  renderFrameList();
  drawPreview();
  saveDraftSoon();
});
</code></pre>
<p><code>Math.min(index, state.frames.length)</code> puts the frame back at the end if the list got shorter in the meantime.</p>
<h2 id="heading-building-the-board-settings">Building the Board Settings</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/8a3aec24-4fd1-4f31-8cfc-af63f04b1112.png" alt="The Board settings panel with Layout, Columns, Rows, Paper, Orientation, Frame label, Font and Text size" style="display: block;" width="600" height="400" loading="lazy">

<p>All settings are read into <code>state.opts</code> in one place, with the number fields limited to a sensible range:</p>
<pre><code class="language-javascript">// ---------- Settings ----------
function readSettings() {
  const o = state.opts;
  SETTING_IDS.forEach((id) =&gt; { o[id] = $(id).value; });
  o.cols = Math.min(6, Math.max(1, parseInt(o.cols, 10) || 1));
  o.rows = Math.min(6, Math.max(1, parseInt(o.rows, 10) || 1));
  o.lines = Math.min(6, Math.max(1, parseInt(o.lines, 10) || 1));
}

SETTING_IDS.forEach((id) =&gt; {
  $(id).addEventListener('change', () =&gt; {
    readSettings();
    state.sheet = 0;
    drawPreview();
  });
});

els.boardTitle.addEventListener('input', () =&gt; {
  state.title = els.boardTitle.value.trim();
  drawPreviewSoon();
  saveDraftSoon();
});
</code></pre>
<p>Any change goes back to the first sheet and redraws the preview. The board title is saved as a draft too, because it's part of the user's work.</p>
<p>The four layouts change only the arrangement. The frame data stays the same, so users can switch layouts freely without losing anything.</p>
<h2 id="heading-laying-out-a-storyboard-sheet">Laying Out a Storyboard Sheet</h2>
<p>This is the heart of the tool. Before drawing anything, the code works out <strong>where every box goes</strong>, in PDF points from the top-left corner of the sheet.</p>
<p>Keeping layout separate from drawing means the same layout is used for the small preview on screen and for the 300 dpi PDF. They can't drift apart.</p>
<h3 id="heading-calculating-the-sheet-size">Calculating the Sheet Size</h3>
<pre><code class="language-javascript">// ---------- Layout: where everything goes, in PDF points from the top-left ----------
function sheetSize(o) {
  const [a, b] = PAPERS[o.paper];
  const short = Math.min(a, b);
  const long = Math.max(a, b);
  return o.orient === 'portrait' ? [short, long] : [long, short];
}
</code></pre>
<p>The paper sizes are stored once. Landscape just swaps the short and long sides.</p>
<h3 id="heading-laying-out-the-frame-boxes">Laying Out the Frame Boxes</h3>
<pre><code class="language-javascript">function computeLayout(o, frameCount) {
  const [W, H] = sheetSize(o);
  const short = Math.min(W, H);
  const margin = short * 0.05;
  const gap = 10;
  const cols = o.layout === 'page' ? 1 : o.cols;
  const rows = o.layout === 'page' ? 1 : o.rows;
  const perSheet = cols * rows;
  const sheets = Math.max(1, Math.ceil(frameCount / perSheet));

  const headH = short * 0.045;              // the title row at the top of each sheet
  const top = margin + headH + margin * 0.5;
  const box = { x: margin, y: top, w: W - 2 * margin, h: H - top - margin };
  const sizeScale = { s: 0.85, m: 1, l: 1.2 }[o.textSize];

  const cellW = (box.w - (cols - 1) * gap) / cols;
  const cellH = (box.h - (rows - 1) * gap) / rows;
  const cells = [];

  for (let r = 0; r &lt; rows; r++) {
    for (let c = 0; c &lt; cols; c++) {
      const x = box.x + c * (cellW + gap);
      const y = box.y + r * (cellH + gap);
      const fs = Math.min(13, Math.max(6.5, cellW * 0.05)) * sizeScale;
      const lh = fs * 1.3;

      if (o.layout === 'notes') {
        // picture on the left, title and ruled lines on the right
        const imgW = Math.min(cellW * 0.5, cellH * 1.6);
        const tx = x + imgW + 8;
        cells.push({ img: { x, y, w: imgW, h: cellH }, text: { x: tx, y, w: x + cellW - tx, h: cellH }, fs, lh, notes: true });
      } else {
        // picture on top, text underneath
        const textH = lh * (1.2 + Number(o.lines)) + fs * 0.6;
        const imgH = Math.max(10, cellH - textH);
        cells.push({ img: { x, y, w: cellW, h: imgH }, text: { x, y: y + imgH + fs * 0.6, w: cellW, h: textH - fs * 0.6 }, fs, lh, strip: o.layout === 'strip' });
      }
    }
  }
  return { W, H, margin, headH, perSheet, sheets, cells };
}
</code></pre>
<p>Here's what happens step by step:</p>
<ol>
<li>The margin is <code>5%</code> of the short side, so it scales with the paper.</li>
<li>The "One frame per page" layout is a 1 × 1 grid.</li>
<li>The number of sheets is the number of frames divided by the frames per sheet, rounded up.</li>
<li>A row at the top is kept for the sheet heading.</li>
<li>The remaining box is split into equal cells with a fixed gap.</li>
<li>The font size depends on the cell width (<code>5%</code> of it), kept between <code>6.5</code> and <code>13</code> points, then scaled by the Text size setting.</li>
<li>In most layouts, the picture sits on top and the text underneath. The text area is sized for the label line plus the chosen number of description lines.</li>
<li>In "Panels with notes", the picture is on the left and the text and ruled lines on the right.</li>
</ol>
<p>Each cell ends up with an <code>img</code> box and a <code>text</code> box, and that's all the drawing code needs to know.</p>
<h3 id="heading-fitting-an-image-without-stretching-it">Fitting an Image Without Stretching It</h3>
<p>A cell is rarely the same shape as the picture. Stretching would distort faces and products, and cropping might cut off what matters. So the picture is scaled to fit inside the box, keeping its proportions, and centered:</p>
<pre><code class="language-javascript">function fitContain(imgW, imgH, box) {
  const s = Math.min(box.w / imgW, box.h / imgH);
  const w = imgW * s;
  const h = imgH * s;
  return { x: box.x + (box.w - w) / 2, y: box.y + (box.h - h) / 2, w, h };
}
</code></pre>
<p>This is the same idea as <code>object-fit: contain</code> in CSS. The smaller of the two scale factors wins, so the whole picture always fits.</p>
<h2 id="heading-drawing-a-sheet-on-the-canvas">Drawing a Sheet on the Canvas</h2>
<h3 id="heading-wrapping-text-into-lines">Wrapping Text into Lines</h3>
<p>Canvas has no automatic line wrapping. <code>fillText</code> draws one line, however long it is. So you measure words with <code>measureText</code> and build the lines yourself:</p>
<pre><code class="language-javascript">// ---------- Text ----------
function wrapText(ctx, text, maxWidth, maxLines) {
  const words = String(text).trim().split(/\s+/).filter(Boolean);
  const lines = [];
  let line = '';
  for (const word of words) {
    const test = line ? line + ' ' + word : word;
    if (ctx.measureText(test).width &lt;= maxWidth || !line) {
      line = test;
    } else {
      lines.push(line);
      line = word;
    }
  }
  if (line) lines.push(line);

  if (lines.length &gt; maxLines) {
    lines.length = maxLines;
    let last = lines[maxLines - 1];
    while (last &amp;&amp; ctx.measureText(last + '…').width &gt; maxWidth) last = last.slice(0, -1);
    lines[maxLines - 1] = last.trimEnd() + '…';
  }
  return lines;
}
</code></pre>
<p>If the description is longer than the lines available, the last line ends with an ellipsis, so the user can see that text was cut.</p>
<h3 id="heading-drawing-labels-titles-and-durations">Drawing Labels, Titles and Durations</h3>
<pre><code class="language-javascript">function frameLabel(o, index) {
  if (o.label === 'number') return String(index + 1);
  if (o.label === 'scene') return `Scene ${index + 1}`;
  if (o.label === 'shot') return `Shot ${index + 1}`;
  return '';
}

function drawFrameText(ctx, o, cell, frame, index, k) {
  const fs = cell.fs * k;
  const lh = cell.lh * k;
  const x = cell.text.x * k;
  const w = cell.text.w * k;
  let y = cell.text.y * k + fs;

  ctx.fillStyle = '#16181b';
  ctx.textBaseline = 'alphabetic';

  // Line 1: label and title on the left, duration on the right
  const dur = formatDuration(frame.dur);
  let room = w;
  if (dur) {
    ctx.font = `${fs}px ${FONTS.mono}`;
    ctx.textAlign = 'right';
    ctx.fillText(dur, x + w, y);
    room -= ctx.measureText(dur).width + fs;
  }
  ctx.textAlign = 'left';
  const head = [frameLabel(o, index), frame.title.trim()].filter(Boolean).join('  ');
  if (head) {
    ctx.font = `bold ${fs}px ${FONTS[o.font]}`;
    ctx.fillText(wrapText(ctx, head, room, 1)[0] || '', x, y);
  }
  y += lh * 1.2;

  // Description, wrapped and cut to the chosen number of lines
  ctx.font = `${fs}px ${FONTS[o.font]}`;
  const maxLines = cell.notes ? Math.floor((cell.text.h * k - lh * 1.2) / lh) : Number(o.lines);
  const lines = frame.desc.trim() ? wrapText(ctx, frame.desc, w, maxLines) : [];
  lines.forEach((line, j) =&gt; ctx.fillText(line, x, y + j * lh));

  // Ruled lines for handwritten notes
  if (cell.notes) {
    ctx.strokeStyle = '#c9c6bd';
    ctx.lineWidth = Math.max(1, 0.6 * k);
    const bottom = (cell.text.y + cell.text.h) * k;
    for (let ly = y + lines.length * lh; ly &lt; bottom - 2; ly += lh * 1.25) {
      ctx.beginPath();
      ctx.moveTo(x, ly);
      ctx.lineTo(x + w, ly);
      ctx.stroke();
    }
  }
}
</code></pre>
<p>The parameter <code>k</code> is the scale from points to pixels. All positions come from the layout in points and are multiplied by <code>k</code> just before drawing. That's what lets the same function draw a 600-pixel preview and a 300 dpi PDF page.</p>
<p>The duration is drawn first, right-aligned, and the space it takes is subtracted from the room left for the label and title. That way a long title never runs into the duration.</p>
<h3 id="heading-drawing-the-whole-sheet">Drawing the Whole Sheet</h3>
<p><code>drawSheet</code> draws the heading, then each frame on the sheet:</p>
<pre><code class="language-javascript">// ---------- Drawing one sheet ----------
// k turns PDF points into canvas pixels. With mode 'preview' the pictures are
// drawn too; with mode 'overlay' their boxes are left transparent for the PDF.
async function drawSheet(ctx, o, L, sheetIndex, k, mode) {
  const W = L.W * k;
  const H = L.H * k;
  const placed = [];

  ctx.clearRect(0, 0, W, H);
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, W, H);

  // Sheet heading: title on the left, total time and sheet number on the right
  const headFs = L.headH * 0.6 * k;
  const base = (L.margin + L.headH * 0.78) * k;
  const total = totalDuration();
  const right = [total ? `Total ${formatDuration(total)}` : '', `Sheet ${sheetIndex + 1} of ${L.sheets}`].filter(Boolean).join(', ');
  ctx.font = `${headFs * 0.72}px ${FONTS.mono}`;
  ctx.fillStyle = '#55585e';
  ctx.textAlign = 'right';
  ctx.fillText(right, W - L.margin * k, base);
  if (state.title) {
    ctx.font = `bold ${headFs}px ${FONTS[o.font]}`;
    ctx.fillStyle = '#16181b';
    ctx.textAlign = 'left';
    ctx.fillText(state.title, L.margin * k, base);
  }
  ctx.strokeStyle = '#c9c6bd';
  ctx.lineWidth = Math.max(1, 0.75 * k);
  ctx.beginPath();
  ctx.moveTo(L.margin * k, (L.margin + L.headH) * k);
  ctx.lineTo(W - L.margin * k, (L.margin + L.headH) * k);
  ctx.stroke();

  const start = sheetIndex * L.perSheet;
  const items = state.frames.slice(start, start + L.perSheet);

  for (let i = 0; i &lt; items.length; i++) {
    const cell = L.cells[i];
    const frame = items[i];

    // Film strip: a dark band with sprocket holes behind the picture
    if (cell.strip) {
      const b = cell.img;
      const hole = b.h * 0.08;
      ctx.fillStyle = '#16181b';
      ctx.fillRect(b.x * k, b.y * k, b.w * k, b.h * k);
      ctx.fillStyle = '#ffffff';
      for (let hx = b.x + hole; hx + hole &lt; b.x + b.w; hx += hole * 2) {
        ctx.fillRect(hx * k, (b.y + hole * 0.3) * k, hole * k, hole * 0.5 * k);
        ctx.fillRect(hx * k, (b.y + b.h - hole * 0.8) * k, hole * k, hole * 0.5 * k);
      }
    }

    const area = cell.strip
      ? { x: cell.img.x, y: cell.img.y + cell.img.h * 0.12, w: cell.img.w, h: cell.img.h * 0.76 }
      : cell.img;
    const rect = fitContain(frame.w, frame.h, area);
    placed.push({ frame, rect });

    const px = { x: Math.round(rect.x * k), y: Math.round(rect.y * k), w: Math.round(rect.w * k), h: Math.round(rect.h * k) };
    if (mode === 'overlay') {
      ctx.clearRect(px.x, px.y, px.w, px.h);
    } else {
      if (!frame.thumbPic) frame.thumbPic = await decodeImage(frame.thumb);
      ctx.drawImage(frame.thumbPic, px.x, px.y, px.w, px.h);
    }
    if (!cell.strip) {
      ctx.strokeStyle = '#16181b';
      ctx.lineWidth = Math.max(1, 0.9 * k);
      ctx.strokeRect(cell.img.x * k, cell.img.y * k, cell.img.w * k, cell.img.h * k);
    }
    drawFrameText(ctx, o, cell, frame, start + i, k);
  }
  return placed;
}
</code></pre>
<p>The <code>mode</code> parameter is the important trick here:</p>
<ul>
<li>In <code>'preview'</code> mode, the pictures are drawn from the thumbnails.</li>
<li>In <code>'overlay'</code> mode, the picture areas are <strong>cleared</strong> to transparent, and the function returns where each picture should go.</li>
</ul>
<p>You'll see why in the PDF section. For the film strip, the dark band and the sprocket holes are drawn first, and the picture sits in the middle of the band.</p>
<h2 id="heading-previewing-the-sheets">Previewing the Sheets</h2>
<p>The preview draws the current sheet at the canvas's on-screen width, multiplied by the device pixel ratio so it stays sharp on high-density screens:</p>
<pre><code class="language-javascript">// ---------- Preview ----------
let previewTimer = null;
function drawPreviewSoon() {
  clearTimeout(previewTimer);
  previewTimer = setTimeout(drawPreview, 150);
}

async function drawPreview() {
  if (!state.frames.length) return;
  const o = state.opts;
  const L = computeLayout(o, state.frames.length);
  state.sheet = Math.min(state.sheet, L.sheets - 1);

  // Draw at the canvas's on-screen width, sharp on high-density screens
  const cssWidth = els.canvas.clientWidth || 600;
  const k = (cssWidth * Math.min(2, window.devicePixelRatio || 1)) / L.W;
  els.canvas.width = Math.round(L.W * k);
  els.canvas.height = Math.round(L.H * k);
  await drawSheet(els.canvas.getContext('2d'), o, L, state.sheet, k, 'preview');

  els.sheetInfo.textContent = `Sheet ${state.sheet + 1} of ${L.sheets}`;
  els.prevBtn.disabled = state.sheet === 0;
  els.nextBtn.disabled = state.sheet &gt;= L.sheets - 1;
}

els.prevBtn.addEventListener('click', () =&gt; { state.sheet--; drawPreview(); });
els.nextBtn.addEventListener('click', () =&gt; { state.sheet++; drawPreview(); });
</code></pre>
<p>The device pixel ratio is capped at 2. A 3× phone screen would otherwise create a canvas nine times the size of the CSS box, which is slow and adds little you can see.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/302d3915-0eec-4a62-a53f-85a617bd7c5b.png" alt="The preview of a grid sheet with 6 frames, the sheet title, total time and &quot;Sheet 1 of 2&quot;" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-saving-a-draft-with-indexeddb">Saving a Draft with IndexedDB</h2>
<p>Writing descriptions for 30 frames takes time. Losing that work to an accidental reload is frustrating, so the tool saves a draft as the user works.</p>
<p><code>localStorage</code> won't do here. It only stores strings, and most browsers limit it to about 5 MB, which is less than two phone photos. IndexedDB can store <code>Blob</code> objects directly and allows far more space.</p>
<h3 id="heading-opening-the-database">Opening the Database</h3>
<pre><code class="language-javascript">// ---------- Draft in IndexedDB ----------
const DB_NAME = 'image-storyboard';
let dbPromise = null;

function openDb() {
  if (!dbPromise) {
    dbPromise = new Promise((resolve, reject) =&gt; {
      const req = indexedDB.open(DB_NAME, 1);
      req.onupgradeneeded = () =&gt; req.result.createObjectStore('drafts');
      req.onsuccess = () =&gt; resolve(req.result);
      req.onerror = () =&gt; reject(req.error);
    });
  }
  return dbPromise;
}

async function dbRun(mode, work) {
  const db = await openDb();
  return new Promise((resolve, reject) =&gt; {
    const tx = db.transaction('drafts', mode);
    const result = work(tx.objectStore('drafts'));
    tx.oncomplete = () =&gt; resolve(result &amp;&amp; result.result);
    tx.onerror = () =&gt; reject(tx.error);
  });
}
</code></pre>
<p><code>dbRun</code> wraps a transaction in a Promise. It resolves when the transaction completes, so a write is only reported as done once it's actually stored.</p>
<h3 id="heading-saving-the-draft">Saving the Draft</h3>
<pre><code class="language-javascript">let saveTimer = null;
function saveDraftSoon() {
  clearTimeout(saveTimer);
  saveTimer = setTimeout(saveDraft, 800);
}

function saveDraft() {
  const draft = {
    title: state.title,
    savedAt: Date.now(),
    frames: state.frames.map(({ blob, name, title, desc, dur }) =&gt; ({ blob, name, title, desc, dur })),
  };
  return dbRun('readwrite', (store) =&gt; store.put(draft, 'current')).catch(() =&gt; {
    els.resultText.textContent = 'This browser could not save a draft. Download the PDF before closing the tab.';
  });
}
</code></pre>
<p>The draft stores the original image files as Blobs, along with the text the user typed. Thumbnails and object URLs aren't stored, because they can be made again from the files.</p>
<p><code>saveDraftSoon</code> waits until the user pauses for 800 ms, so typing a description doesn't write to the database on every key press.</p>
<p>If saving fails, for example in a private window with storage blocked, the tool tells the user to download the PDF before closing the tab instead of failing silently.</p>
<h3 id="heading-restoring-the-draft">Restoring the Draft</h3>
<p>When the page loads, the tool checks for a draft and offers to restore it:</p>
<pre><code class="language-javascript">async function checkDraft() {
  try {
    const draft = await dbRun('readonly', (store) =&gt; store.get('current'));
    if (!draft || !draft.frames.length) return;
    els.draftText.textContent = `You have a saved storyboard with ${draft.frames.length} frames.`;
    els.draftBar.hidden = false;
  } catch (err) { /* no storage: nothing to restore */ }
}

els.restoreBtn.addEventListener('click', async () =&gt; {
  const draft = await dbRun('readonly', (store) =&gt; store.get('current'));
  for (const saved of draft.frames) {
    const file = new File([saved.blob], saved.name, { type: saved.blob.type });
    const frame = await makeFrame(file);
    Object.assign(frame, { title: saved.title, desc: saved.desc, dur: saved.dur });
    state.frames.push(frame);
  }
  state.title = draft.title || '';
  els.boardTitle.value = state.title;
  showWorkspace();
  renderFrameList();
  drawPreview();
});

els.discardBtn.addEventListener('click', () =&gt; {
  dbRun('readwrite', (store) =&gt; store.delete('current'));
  els.draftBar.hidden = true;
});
</code></pre>
<p>Each saved Blob goes back through <code>makeFrame</code>, so restored frames get fresh thumbnails, and then the saved text is copied onto them.</p>
<h2 id="heading-generating-the-pdf-with-pdf-lib">Generating the PDF with PDF-lib</h2>
<p>The simplest way to make the PDF would be to draw each whole sheet on a canvas, with the pictures, and put that canvas in the PDF as one image. It works, but it forces a choice:</p>
<ul>
<li>Save it as PNG and the photos make the file huge.</li>
<li>Save it as JPEG and the text and thin lines get blurry edges.</li>
</ul>
<p>So the tool uses <strong>two layers</strong> on each page:</p>
<ol>
<li><strong>Pictures</strong> as JPEG, each at the resolution the user chose, placed exactly in its box</li>
<li><strong>Text, labels and lines</strong> as one transparent PNG at 300 dpi, covering the whole page on top</li>
</ol>
<p>JPEG is good for photos, and PNG keeps text sharp. This is why <code>drawSheet</code> has the <code>'overlay'</code> mode that leaves holes where the pictures go.</p>
<h3 id="heading-turning-each-picture-into-a-jpeg">Turning Each Picture into a JPEG</h3>
<pre><code class="language-javascript">// ---------- Making the PDF ----------
async function imageAsJpeg(frame, widthPx, heightPx) {
  const pic = await decodeImage(frame.blob);
  const c = document.createElement('canvas');
  c.width = Math.max(1, Math.round(widthPx));
  c.height = Math.max(1, Math.round(heightPx));
  const ctx = c.getContext('2d');
  ctx.fillStyle = '#ffffff';              // transparent PNGs get a white background
  ctx.fillRect(0, 0, c.width, c.height);
  ctx.imageSmoothingQuality = 'high';
  ctx.drawImage(pic, 0, 0, c.width, c.height);
  if (pic.close) pic.close();
  const blob = await canvasToBlob(c, 'image/jpeg', 0.9);
  return new Uint8Array(await blob.arrayBuffer());
}
</code></pre>
<p>The picture is decoded again from the <strong>original</strong> file, not from the thumbnail, so the PDF has full quality.</p>
<h3 id="heading-building-the-pages">Building the Pages</h3>
<pre><code class="language-javascript">async function buildPdf() {
  const { PDFDocument } = PDFLib;
  const o = state.opts;
  const L = computeLayout(o, state.frames.length);
  const dpi = Number(els.quality.value);
  const k = 300 / 72;                         // text layer at 300 dpi

  const pdf = await PDFDocument.create();
  for (let s = 0; s &lt; L.sheets; s++) {
    els.resultText.textContent = `Making sheet ${s + 1} of ${L.sheets}...`;
    const page = pdf.addPage([L.W, L.H]);

    // 1. Text, labels and lines on a canvas, with holes where the pictures go
    const c = document.createElement('canvas');
    c.width = Math.round(L.W * k);
    c.height = Math.round(L.H * k);
    const placed = await drawSheet(c.getContext('2d'), o, L, s, k, 'overlay');

    // 2. Each picture as a JPEG at the chosen resolution, placed in its hole
    for (const { frame, rect } of placed) {
      const scale = Math.min(1, (rect.w * dpi / 72) / frame.w);
      const jpg = await pdf.embedJpg(await imageAsJpeg(frame, frame.w * scale, frame.h * scale));
      // PDF y runs from the bottom of the page, the canvas y from the top
      page.drawImage(jpg, { x: rect.x, y: L.H - rect.y - rect.h, width: rect.w, height: rect.h });
    }

    // 3. The text layer on top, as one transparent PNG covering the page
    const pngBlob = await canvasToBlob(c, 'image/png');
    const png = await pdf.embedPng(new Uint8Array(await pngBlob.arrayBuffer()));
    page.drawImage(png, { x: 0, y: 0, width: L.W, height: L.H });
    c.width = 1;                               // free the canvas memory
  }

  pdf.setTitle(state.title || 'Storyboard');
  return pdf.save();
}
</code></pre>
<p>Here's what happens on each page:</p>
<ol>
<li><code>addPage([L.W, L.H])</code> creates a page in points, the same units as the layout.</li>
<li>The text layer is drawn at <code>k = 300 / 72</code>, which is 300 pixels per inch.</li>
<li>Each picture is resized to the chosen dpi for the size it has on the page. A 4000-pixel photo shown 2 inches wide only needs 600 pixels at 300 dpi, so the file stays small. <code>Math.min(1, ...)</code> makes sure small pictures are never enlarged.</li>
<li>The pictures are drawn first, then the transparent PNG on top of them.</li>
</ol>
<p>Note the y coordinate: <code>L.H - rect.y - rect.h</code>. The layout and the canvas measure y from the <strong>top</strong> of the page, but PDF measures y from the <strong>bottom</strong>. Forgetting this flip puts every picture upside down in the page, the classic PDF-lib mistake.</p>
<p>Setting <code>c.width = 1</code> after use frees the canvas memory right away, which matters on phones when there are many sheets.</p>
<h2 id="heading-renaming-and-downloading">Renaming and Downloading</h2>
<p>The file name comes from a text field, cleaned of characters that aren't allowed in file names:</p>
<pre><code class="language-javascript">// ---------- Download ----------
function cleanFileName(name) {
  const n = name.trim().replace(/\.pdf$/i, '').replace(/[\\/:*?"&lt;&gt;|]+/g, '-');
  return (n || 'storyboard') + '.pdf';
}

function formatSize(bytes) {
  return bytes &lt; 1024 * 1024 ? `${Math.round(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}

els.downloadBtn.addEventListener('click', async () =&gt; {
  if (!state.frames.length) return;
  els.downloadBtn.disabled = true;
  try {
    const bytes = await buildPdf();
    const name = cleanFileName(els.fileName.value);
    const url = URL.createObjectURL(new Blob([bytes], { type: 'application/pdf' }));
    const a = document.createElement('a');
    a.href = url;
    a.download = name;
    a.click();
    setTimeout(() =&gt; URL.revokeObjectURL(url), 60000);
    els.resultText.textContent = `Saved ${name} (${formatSize(bytes.length)}).`;
  } catch (err) {
    console.error(err);
    els.resultText.textContent = 'The PDF could not be made. Try fewer images or the 150 dpi setting.';
  } finally {
    els.downloadBtn.disabled = false;
  }
});
</code></pre>
<p>The object URL is revoked after a minute, which is long enough for the download to start and frees the memory afterwards. The button is disabled while the PDF is being made, so a double click can't start two exports.</p>
<p>Finally, "Start over" clears the state, the draft and the object URLs. The last two lines of the file read the default settings and check for a saved draft when the page loads:</p>
<pre><code class="language-javascript">// ---------- Start over ----------
els.resetBtn.addEventListener('click', () =&gt; {
  clearTimeout(saveTimer);
  state.frames.forEach((f) =&gt; URL.revokeObjectURL(f.thumbUrl));
  state.frames = [];
  state.title = '';
  state.sheet = 0;
  state.lastDeleted = null;
  els.boardTitle.value = '';
  els.undoBtn.hidden = true;
  els.resultText.textContent = '';
  els.workspace.hidden = true;
  els.uploadArea.hidden = false;
  dbRun('readwrite', (store) =&gt; store.delete('current')).catch(() =&gt; {});
});

readSettings();
checkDraft();
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/fdad77c5-a9f5-4906-8cad-f54190b9f3b2.png" alt="Fille rename, image qulaity download various option" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-demo-how-the-image-storyboard-tool-works">Demo: How the Image Storyboard Tool Works</h2>
<p>Here's the whole workflow in the finished tool.</p>
<h3 id="heading-step-1-add-your-images">Step 1: Add Your Images</h3>
<p>Drop a folder's worth of images on the page or click Select images. They're sorted by file name, so <code>shot-1</code>, <code>shot-2</code> … <code>shot-10</code> land in the right order.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/5ad4654c-d0d8-49f6-b6c1-737407aa1c1d.png" alt="5ad4654c-d0d8-49f6-b6c1-737407aa1c1d" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-2-put-the-frames-in-order">Step 2: Put the Frames in Order</h3>
<p>Drag a thumbnail onto another card, or use the Up and Down buttons.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/ffc1cdbd-2114-45e1-8f57-26a5d2557d01.png" alt="A frame being dragged to a new position" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-3-write-the-script">Step 3: Write the Script</h3>
<p>Give each frame a title, a description and a duration. The total running time updates as you type.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/015b8081-985b-4965-b392-43630e890bdc.png" alt=" Several frame cards filled in" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-4-choose-a-layout">Step 4: Choose a Layout</h3>
<p>Pick one frame per page, a grid, panels with notes or a film strip, then set the paper size and orientation.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/7e512b96-8a4e-42a4-9dc6-4c0d7960c9d1.png" alt="The settings panel with a layout selected" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-5-check-the-preview">Step 5: Check the Preview</h3>
<p>Use Previous and Next to look at every sheet before you download.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/3e781d95-ca13-417a-9e2f-bf88e6112cba.png" alt="The preview of the frames" style="display: block;" width="600" height="400" loading="lazy">

<h3 id="heading-step-6-download-the-pdf">Step 6: Download the PDF</h3>
<p>Type a file name, choose the image quality and click Download PDF.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/d9690b9d-7a43-4421-9167-a95d8813b2b3.png" alt="The downloaded PDF open in a PDF viewer" style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-performance-tips">Performance Tips</h2>
<p><strong>Use thumbnails for everything on screen.</strong> The preview redraws often, while the user types and changes settings. Drawing 1000-pixel thumbnails instead of full photos keeps it fast. Only the PDF export touches the original files.</p>
<p><strong>Decode thumbnails once.</strong> In <code>drawSheet</code>, each frame keeps its decoded thumbnail in <code>frame.thumbPic</code>, so switching sheets doesn't decode the same image again.</p>
<p><strong>Process images one at a time.</strong> Reading or exporting dozens of large photos with <code>Promise.all</code> can use more memory than a phone has. A simple <code>for</code> loop with <code>await</code> keeps only one large image in memory at a time.</p>
<p><strong>Size pictures for the page, not the camera.</strong> A picture's pixel size in the PDF should depend on how big it is on the page and the chosen dpi. That one line in <code>buildPdf</code> is often the difference between a 3 MB file and a 60 MB file.</p>
<p><strong>Release memory as you go.</strong> Call <code>close()</code> on an <code>ImageBitmap</code> when you're done with it, set used canvases to <code>width = 1</code>, and revoke object URLs you no longer need.</p>
<h2 id="heading-common-mistakes">Common Mistakes</h2>
<p><strong>Sideways phone photos.</strong> If you read an image's size or draw it without applying EXIF orientation, portrait photos come out landscape. Use <code>createImageBitmap(blob, { imageOrientation: 'from-image' })</code>.</p>
<p><strong>Stretched pictures.</strong> Drawing an image straight into a cell with <code>drawImage(img, x, y, cellW, cellH)</code> stretches it. Always fit it with a "contain" calculation like <code>fitContain</code> first.</p>
<p><strong>Wrong order of files.</strong> The order files arrive from a file picker or a drop isn't guaranteed. Sort them yourself, and use a numeric sort so <code>shot-10</code> comes after <code>shot-9</code>.</p>
<p><strong>Forgetting to flip the y axis.</strong> Canvas y goes down from the top, PDF y goes up from the bottom. Convert with <code>pageHeight - y - height</code> when placing anything with PDF-lib.</p>
<p><strong>Black backgrounds on transparent PNGs.</strong> JPEG has no transparency. Fill the canvas with white before drawing a PNG you'll save as JPEG.</p>
<p><strong>Rebuilding the list while the user types.</strong> Re-rendering inputs on every key press moves the cursor and loses focus. Update the state from the <code>input</code> event and only rebuild the list when the order changes.</p>
<p><strong>Canvases that are too large.</strong> Browsers limit canvas size, and phones have tight limits. An A3 page at 300 dpi is about 4960 × 3508 pixels, which is fine, but don't multiply that by the device pixel ratio as well.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you built a browser-based tool that turns a set of images into storyboard sheets and a print-ready PDF.</p>
<p>You learned how to apply phone photo rotation with <code>createImageBitmap</code>, sort file names numerically, keep layout math in PDF points so the preview and the PDF always match, wrap text on a canvas, save a draft of images and text in IndexedDB, and build a two-layer PDF with sharp text and compact photos using PDF-lib.</p>
<p>All of it runs locally in the browser, so the images stay on the user's device.</p>
<p>You can try the full version of this tool, with more options such as sheet colors, a handwritten font, one PDF per frame and PNG export, at <a href="https://allinonetools.net/image-storyboard-to-pdf/">Image Storyboard to PDF</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a PDF Storyboard Generator Using JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ PDF files are commonly used to share presentations, scripts, reports, lesson materials, comic pages, and other visual documents. But reviewing a long PDF page by page can take time, especially when so ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-pdf-storyboard-generator-javascript/</link>
                <guid isPermaLink="false">6aee2d6e123f77519047915d</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ pdf ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bhavin Sheth ]]>
                </dc:creator>
                <pubDate>Fri, 06 Nov 2026 19:41:34 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/e8109e42-db7b-4690-9d2b-2be82ab57943.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>PDF files are commonly used to share presentations, scripts, reports, lesson materials, comic pages, and other visual documents. But reviewing a long PDF page by page can take time, especially when someone needs to understand the overall sequence of scenes, slides, or visual content.</p>
<p>A storyboard provides a more organized way to review this information. Instead of opening every page individually, users can arrange selected PDF pages into a single sheet containing multiple panels. Each panel can include a page number, a caption, and a visual preview of the original page.</p>
<p>In this tutorial, we'll explore how to build a browser-based PDF Storyboard Generator using JavaScript, PDF.js, and PDF-lib.</p>
<p>The application takes pages from an existing PDF and arranges them into printable storyboard sheets. Users can choose different layouts, select the pages they want to include, add captions, customize the appearance, preview the result, and download the finished storyboard.</p>
<p>The application runs directly in the browser. The uploaded PDF is processed locally rather than uploaded to the website's server.</p>
<p>We'll examine the implementation step by step, including PDF rendering, page selection, caption handling, layout calculations, preview generation, and file export.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><a href="#heading-what-is-a-pdf-storyboard-generator">What Is a PDF Storyboard Generator?</a></li>
<li><a href="#heading-main-features-of-the-application">Main Features of the Application</a></li>
<li><a href="#heading-understanding-the-browser-based-workflow">Understanding the Browser-Based Workflow</a></li>
<li><a href="#heading-project-setup">Project Setup</a></li>
<li><a href="#heading-libraries-used">Libraries Used</a></li>
<li><a href="#heading-preparing-the-html-workspace">Preparing the HTML Workspace</a></li>
<li><a href="#heading-selecting-the-main-dom-elements">Selecting the Main DOM Elements</a></li>
<li><a href="#heading-defining-important-configuration-values">Defining Important Configuration Values</a></li>
<li><a href="#heading-understanding-the-application-state">Understanding the Application State</a></li>
<li><a href="#heading-uploading-a-pdf">Uploading a PDF</a></li>
<li><a href="#heading-loading-the-pdf-with-pdfjs">Loading the PDF with PDF.js</a></li>
<li><a href="#heading-measuring-pdf-pages">Measuring PDF Pages</a></li>
<li><a href="#heading-rendering-pdf-pages-on-canvas">Rendering PDF Pages on Canvas</a></li>
<li><a href="#heading-reusing-rendered-page-previews">Reusing Rendered Page Previews</a></li>
<li><a href="#heading-reading-text-from-pdf-pages">Reading Text from PDF Pages</a></li>
<li><a href="#heading-filling-empty-captions-automatically">Filling Empty Captions Automatically</a></li>
<li><a href="#heading-updating-the-preview">Updating the Preview</a></li>
<li><a href="#heading-choosing-the-storyboard-layout">Choosing the Storyboard Layout</a></li>
<li><a href="#heading-controlling-rows-columns-and-paper-size">Controlling Rows, Columns, and Paper Size</a></li>
<li><a href="#heading-selecting-pdf-pages-and-their-order">Selecting PDF Pages and Their Order</a></li>
<li><a href="#heading-adding-panel-labels">Adding Panel Labels</a></li>
<li><a href="#heading-drawing-the-storyboard-sheet">Drawing the Storyboard Sheet</a></li>
<li><a href="#heading-updating-the-live-preview">Updating the Live Preview</a></li>
<li><a href="#heading-adjusting-caption-appearance">Adjusting Caption Appearance</a></li>
<li><a href="#heading-navigating-between-storyboard-sheets">Navigating Between Storyboard Sheets</a></li>
<li><a href="#heading-reading-scanned-pages-with-ocr">Reading Scanned Pages with OCR</a></li>
<li><a href="#heading-generating-the-final-storyboard-pdf">Generating the Final Storyboard PDF</a></li>
<li><a href="#heading-downloading-png-storyboard-sheets">Downloading PNG Storyboard Sheets</a></li>
<li><a href="#heading-downloading-individual-page-pictures">Downloading Individual Page Pictures</a></li>
<li><a href="#heading-performance-and-important-considerations">Performance and Important Considerations</a></li>
<li><a href="#heading-demo-pdf-storyboard-generator">Demo: PDF Storyboard Generator</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-what-is-a-pdf-storyboard-generator">What Is a PDF Storyboard Generator?</h2>
<p>A PDF Storyboard Generator converts selected pages from an existing PDF into a structured visual sheet.</p>
<p>For example, imagine that you have a PDF containing 20 presentation slides. Instead of sharing all 20 slides separately, you can arrange them into a storyboard containing three columns and two rows per sheet.</p>
<p>Each panel displays a scaled version of its original PDF page. You can also add a number or label and write a short description underneath.</p>
<p>The same approach can be useful for:</p>
<ul>
<li>Reviewing presentation slides.</li>
<li>Organizing comic pages.</li>
<li>Planning video scenes.</li>
<li>Preparing visual scripts.</li>
<li>Reviewing scanned documents.</li>
<li>Creating printable teaching materials.</li>
<li>Organizing page sequences for creative projects.</li>
</ul>
<p>The application doesn't create new scenes or draw illustrations. It arranges existing PDF pages into a storyboard layout.</p>
<h2 id="heading-main-features-of-the-application">Main Features of the Application</h2>
<p>Before writing the code, let's understand the features we're going to implement.</p>
<h3 id="heading-1-pdf-upload">1. PDF Upload</h3>
<p>Users can select a PDF from their device or drag and drop it into the upload area.</p>
<h3 id="heading-2-multiple-storyboard-layouts">2. Multiple Storyboard Layouts</h3>
<p>The application supports three layouts:</p>
<ul>
<li>Grid: Arranges pages in rows and columns.</li>
<li>Panels with notes: Provides space for written notes alongside the page panels.</li>
<li>Film strip: Arranges pages in a film-strip style.</li>
</ul>
<h3 id="heading-3-page-selection-and-ordering"><strong>3. Page Selection and Ordering</strong></h3>
<p>Users can choose which PDF pages should appear in the storyboard. They can also specify a custom order rather than following the original PDF sequence.</p>
<h3 id="heading-4-captions">4. Captions</h3>
<p>Users can type captions manually, fill empty captions using extracted PDF page text, or use OCR to read text from scanned pages.</p>
<h3 id="heading-5-customization">5. Customization</h3>
<p>Users can customize the paper size, orientation, number of columns and rows, panel labels, sheet colors, caption font, text size, spacing, and panel frames.</p>
<h3 id="heading-6-live-preview">6. Live Preview</h3>
<p>The application generates a preview of the storyboard sheets. Users can review the arrangement before downloading the final output.</p>
<p><strong>7. Multiple Export Formats</strong></p>
<p>Users can export their work as:</p>
<ul>
<li>A PDF storyboard.</li>
<li>PNG storyboard sheets.</li>
<li>A ZIP file containing individual page pictures.</li>
</ul>
<p>The PDF export preserves original page content as vectors when possible, helping maintain sharp text and graphics.</p>
<h2 id="heading-understanding-the-browser-based-workflow">Understanding the Browser-Based Workflow</h2>
<p>The application follows a straightforward process.</p>
<ol>
<li>The user selects or drops a PDF file into the upload area.</li>
<li>PDF.js loads the document and renders its pages.</li>
<li>The application displays page previews and caption fields.</li>
<li>The user selects pages, changes their order, and enters captions.</li>
<li>The user configures the storyboard layout and appearance.</li>
<li>JavaScript calculates the position and dimensions of every panel.</li>
<li>The preview is updated to reflect the selected settings.</li>
<li>PDF-lib and browser canvas functionality are used to generate the requested output.</li>
<li>The browser downloads the finished file.</li>
</ol>
<p><strong>PDF Upload Workspace</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/1d23ecf5-1677-4549-84e1-03a08e8943eb.png" alt="PDF Storyboard Generator upload workspace with a drag-and-drop area and PDF selection button." style="display: block;" width="600" height="400" loading="lazy">

<p><strong>Panels and Captions</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/996d2382-8020-4ddc-b1b8-5956ec86bbdd.png" alt="PDF pages displayed in a storyboard workspace with page previews, caption fields, and OCR controls." style="display: block;" width="600" height="400" loading="lazy">

<p><strong>Board Settings and Preview</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/882dbe78-4c8c-4d21-aa64-6519fea5a4bf.png" alt="Storyboard settings panel showing layout, page selection, paper size, orientation, captions, and a live preview." style="display: block;" width="600" height="400" loading="lazy">

<p><strong>Final Storyboard Preview</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/74d7c855-7a6f-44f0-83c2-09efe38a5c3c.png" alt="Final PDF storyboard preview with three numbered panels and captions arranged on an A4 landscape sheet." style="display: block;" width="600" height="400" loading="lazy">

<p><strong>Downloaded PDF</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/64397878-ad42-46eb-b5b6-d39fbf104335.png" alt="Downloaded PDF storyboard containing three arranged panels with page numbers and captions." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-project-setup">Project Setup</h2>
<p>Before writing the JavaScript functionality, we need to understand how the application is organized.</p>
<p>The PDF Storyboard Generator combines HTML, CSS, and JavaScript. HTML provides the interface, CSS controls the appearance of the workspace and storyboard sheets, and JavaScript handles PDF processing, page previews, captions, layout calculations, and downloads.</p>
<p>For a standalone development project, we can organize the files like this:</p>
<pre><code class="language-text">pdf-storyboard-generator/
├── index.html
├── style.css
├── script.js
└── assets/
</code></pre>
<p>The <code>index.html</code> file contains the application structure, including the upload area, page panels, caption fields, board settings, and preview.</p>
<p>The <code>style.css</code> file controls the appearance of the application. It defines the workspace, panel grid, form controls, buttons, preview area, and responsive layout.</p>
<p>The <code>script.js</code> file contains the main application logic. It loads PDF documents, renders their pages, manages captions, processes OCR requests, calculates storyboard layouts, and generates downloadable files.</p>
<p>The <code>assets</code> directory can hold any additional local resources required by the project.</p>
<p>In the existing AllInOneTools implementation, these components are integrated into the website's tool page rather than being deployed as four separate files. The same separation of responsibilities still applies.</p>
<h2 id="heading-libraries-used">Libraries Used</h2>
<p>The application uses three main JavaScript libraries or browser technologies for its PDF and image-processing workflow.</p>
<h3 id="heading-1-pdfjs">1. PDF.js</h3>
<p>We'll use PDF.js to open PDF documents and render their pages inside the browser.</p>
<p>It allows JavaScript to access individual pages, retrieve their dimensions, create viewports, and draw page content onto an HTML canvas.</p>
<p>For this project, PDF.js is responsible for the original PDF page previews.</p>
<p>The application uses the PDF.js document API to retrieve pages and render them at the required dimensions. This is important because the storyboard must display a visual representation of each selected page before the user downloads the finished sheet.</p>
<h3 id="heading-2-pdf-lib">2. PDF-lib</h3>
<p>We'll use PDF-lib used when generating the final PDF document.</p>
<p>PDF.js and PDF-lib have different responsibilities. PDF.js reads and renders the source document, while PDF-lib creates the new storyboard PDF.</p>
<p>The application uses PDF-lib to create output pages, embed the original PDF pages when possible, and place the finished storyboard elements onto those pages.</p>
<p>Keeping the original PDF pages as vector content helps preserve text and line quality when users zoom in or print the exported document. The implementation also uses a raster-based fallback for password-protected PDFs that can't be loaded through the regular PDF embedding path.</p>
<h3 id="heading-3-tesseractjs">3. Tesseract.js</h3>
<p>This library provides optional Optical Character Recognition (OCR).</p>
<p>Not every PDF contains selectable text. A scanned document, for example, may contain photographs of printed pages instead of actual text data.</p>
<p>When the user selects the OCR option, the application loads Tesseract.js and its English language data. It then processes eligible scanned pages and attempts to extract their text for captions.</p>
<p>OCR is optional, so users don't need to load the OCR engine when they only want to arrange PDF pages and write captions manually.</p>
<p>The following example illustrates how a standalone project could include the libraries through CDN scripts:</p>
<pre><code class="language-html">&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.4.168/pdf.min.js"&gt;&lt;/script&gt;
&lt;script src="https://unpkg.com/pdf-lib/dist/pdf-lib.min.js"&gt;&lt;/script&gt;
&lt;script src="script.js"&gt;&lt;/script&gt;
</code></pre>
<p>For a production application, use library versions that you've tested and configure the matching PDF.js worker file as required by your chosen PDF.js build.</p>
<h3 id="heading-why-these-libraries-work-together">Why These Libraries Work Together</h3>
<p>Each library has a separate responsibility.</p>
<p>PDF.js reads the source PDF and renders its pages. Tesseract.js optionally extracts text from scanned pages. PDF-lib creates the final storyboard PDF.</p>
<p>JavaScript connects these operations and manages the user interface.</p>
<p>This separation makes the application easier to understand and maintain. It also avoids using one library for tasks that are better handled by another.</p>
<h2 id="heading-preparing-the-html-workspace">Preparing the HTML Workspace</h2>
<p>The interface needs several areas to support the complete storyboard workflow.</p>
<p>The upload area accepts the source PDF. The panel area displays rendered pages and caption fields. The board settings area contains layout and appearance controls. Finally, the preview area displays the generated storyboard sheets.</p>
<p>A simplified HTML structure looks like this:</p>
<pre><code class="language-html">&lt;section id="aiot-sb"&gt;
    &lt;div id="aiot-sb-drop"&gt;
        &lt;input
            type="file"
            id="aiot-sb-file-input"
            accept="application/pdf,.pdf"
        &gt;
        &lt;button type="button" data-act="browse"&gt;
            Select a PDF
        &lt;/button&gt;
    &lt;/div&gt;
    &lt;div id="aiot-sb-grid"&gt;&lt;/div&gt;
    &lt;div id="aiot-sb-settings"&gt;&lt;/div&gt;
    &lt;div id="aiot-sb-preview"&gt;&lt;/div&gt;
&lt;/section&gt;
</code></pre>
<p>This is an illustrative structure showing the main interface areas. The actual application contains additional controls, accessibility attributes, and elements for its different operations.</p>
<p>The <code>aiot-sb</code> container provides a common root for the application. JavaScript can use this root to find the relevant interface elements without searching the entire website.</p>
<h2 id="heading-selecting-the-main-dom-elements">Selecting the Main DOM Elements</h2>
<p>JavaScript needs references to the interface elements before it can respond to user actions.</p>
<p>The application starts by finding its root container and checking whether initialization has already taken place:</p>
<pre><code class="language-javascript">var root = document.getElementById("aiot-sb");
if (!root || root.getAttribute("data-aiot-sb-ready")) {
    return;
}
root.setAttribute("data-aiot-sb-ready", "1");
</code></pre>
<p>This prevents the application from initializing again if the script is executed more than once.</p>
<p>The implementation uses a small helper to find elements inside the application:</p>
<pre><code class="language-javascript">function q(selector) {
    return root.querySelector(selector);
}
</code></pre>
<p>For example, <code>q('[data-act="browse"]')</code> finds the button used to open the PDF file picker.</p>
<p>Using a root-specific helper also helps keep the application code organized when the website contains other tools or interface components.</p>
<h2 id="heading-defining-important-configuration-values">Defining Important Configuration Values</h2>
<p>The application needs a few shared configuration values for its layouts and output settings.</p>
<p>For example, it defines supported paper dimensions and font families:</p>
<pre><code class="language-javascript">var MM = 72 / 25.4;
var PAPERS = {
    a4: [595.28, 841.89],
    letter: [612, 792],
    a3: [841.89, 1190.55],
    slide: [405, 720]
};
var PAPER_NAMES = {
    a4: "A4",
    letter: "Letter",
    a3: "A3",
    slide: "16:9 slide"
};
</code></pre>
<p>PDF page dimensions are commonly expressed in points, while some of the storyboard spacing settings are easier to understand in millimeters. The <code>MM</code> conversion value helps translate between these units.</p>
<p>The <code>PAPERS</code> object stores the available page dimensions. The application can use these values when calculating the size of each storyboard sheet.</p>
<p>The <code>PAPER_NAMES</code> object provides readable labels for the corresponding settings.</p>
<p>The application also defines font families for captions and other text:</p>
<pre><code class="language-javascript">var FONTS = {
    sans: "Arial, 'Helvetica Neue', Helvetica, sans-serif",
    serif: "Georgia, 'Times New Roman', serif",
    mono: "'Courier New', Courier, monospace",
    hand: "'Segoe Print', 'Bradley Hand', cursive"
};
</code></pre>
<p>These values allow the storyboard renderer to use different text styles without repeating font definitions throughout the code.</p>
<h2 id="heading-understanding-the-application-state">Understanding the Application State</h2>
<p>The application needs to remember information about the currently loaded PDF, its pages, captions, selected layout, and export process.</p>
<p>Instead of relying on individual variables scattered throughout the application, the implementation groups related information into a shared state object.</p>
<p>For example, the application tracks information such as:</p>
<ul>
<li>The loaded PDF document.</li>
<li>The original PDF bytes.</li>
<li>The current filename.</li>
<li>Page captions.</li>
<li>Page preview data.</li>
<li>Loading and export status.</li>
<li>The OCR worker when OCR is active.</li>
<li>Cancellation and loading tokens.</li>
</ul>
<p>The actual implementation manages these values within its application state and uses them throughout the rendering and export functions.</p>
<p>This becomes especially important when the user changes a caption or layout setting. The application needs to know which values have changed so it can update the storyboard preview without unnecessarily reopening the source document.</p>
<h2 id="heading-uploading-a-pdf">Uploading a PDF</h2>
<p>The first step is allowing users to select a PDF from their device. The PDF Storyboard Generator supports two methods: selecting a file through the file picker or dragging and dropping it into the upload area.</p>
<p>The file input uses the following HTML:</p>
<pre><code class="language-html">&lt;input
    type="file"
    id="aiot-sb-file-input"
    accept="application/pdf,.pdf"
&gt;
</code></pre>
<p>Let's understand the <code>accept</code> attribute:</p>
<ul>
<li><code>application/pdf</code> is the MIME type for PDF files.</li>
<li><code>.pdf</code> is the file extension.</li>
</ul>
<p>A MIME type (Multipurpose Internet Mail Extensions type) identifies the format of a file. Browsers use MIME types to describe the kind of content a file contains. For example, <code>application/pdf</code> identifies a PDF document.</p>
<p>The application checks both the MIME type and the filename extension. This is useful because some browsers or operating systems may provide an empty or incorrect MIME type for a selected file.</p>
<p>The actual application uses this helper:</p>
<pre><code class="language-javascript">function isPdf(file) {
    return file.type === 'application/pdf' ||
        /\.pdf$/i.test(file.name || '');
}
</code></pre>
<p>The first condition checks the file's MIME type. The second checks whether its filename ends with <code>.pdf</code>. The <code>i</code> flag makes the extension check case-insensitive, so filenames such as <code>document.PDF</code> are also accepted.</p>
<p>After validation, both upload methods use the same <code>handleFiles()</code> function. Its initial steps are:</p>
<pre><code class="language-javascript">function handleFiles(list, password) {
    var all = Array.prototype.slice.call(list || []);
    ui.input.value = '';

    if (!all.length) {
        return Promise.resolve();
    }

    var file = all.filter(isPdf)[0];

    if (!file) {
        toast("That isn't a PDF. Choose a PDF file.", 'error');
        return Promise.resolve();
    }

    var note = all.length &gt; 1
        ? ' Only ' + file.name + ' was opened; a storyboard uses one PDF.'
        : '';

    var token = ++state.loadToken;
    var hadDoc = !!state.doc;
    var task, bytes;

    if (hadDoc) {
        ui.fileMeta.textContent = 'Opening ' + file.name + '…';
    }

    setStatus('Opening ' + file.name + '…', true);

    // The remaining function loads and processes the selected PDF.
}
</code></pre>
<p>The function converts the supplied file list into an array and selects the first valid PDF. If no valid PDF is found, it displays an error message and stops.</p>
<p>The <code>loadToken</code> value helps the application distinguish the current loading operation from an older one. This matters when a user selects another document while a previous document is still being processed.</p>
<p>Next, the application waits for the PDF libraries to become available and reads the selected file:</p>
<pre><code class="language-javascript">return engine().then(function () {
    return file.arrayBuffer();
}).then(function (buf) {
    bytes = buf;

    var opts = {
        data: new Uint8Array(buf.slice(0))
    };

    if (password) {
        opts.password = password;
    }

    task = window.pdfjsLib.getDocument(pdfjsOptions(opts));
    return task.promise;
});
</code></pre>
<p>The <code>file.arrayBuffer()</code> method reads the PDF into browser memory. The application converts the data into a <code>Uint8Array</code> and passes it to PDF.js through <code>getDocument()</code>.</p>
<p>If a password was supplied, it's added to the PDF.js options before the document is opened.</p>
<p>The complete function continues by measuring the PDF pages, checking whether the original pages can be embedded as vectors, updating the application state, and displaying the workspace.</p>
<p>This means the selected PDF is processed in the browser. It isn't uploaded to the website's server.</p>
<h2 id="heading-loading-the-pdf-with-pdfjs">Loading the PDF with PDF.js</h2>
<p>Once a file has been selected, the application reads its contents and passes the data to PDF.js.</p>
<p>The PDF.js loading process returns a document object. This object provides access to the document's pages and metadata.</p>
<p>In the actual application, PDF.js is initialized inside the file-loading process. The application first waits for the PDF libraries to load, reads the selected file, and then passes its data to PDF.js.</p>
<pre><code class="language-javascript">return engine().then(function () {
    return file.arrayBuffer();
}).then(function (buf) {
    bytes = buf;

    var opts = {
        data: new Uint8Array(buf.slice(0))
    };

    if (password) {
        opts.password = password;
    }

    task = window.pdfjsLib.getDocument(pdfjsOptions(opts));
    return task.promise;
});
</code></pre>
<p>The <code>engine()</code> function ensures that the required PDF libraries are available before processing begins. The application then uses <code>file.arrayBuffer()</code> to read the selected PDF into browser memory.</p>
<p>The <code>Uint8Array</code> constructor converts the file data into a format that PDF.js can process. If the user has supplied a password, it's added to the PDF.js options before the document is opened.</p>
<p>The <code>getDocument()</code> method starts the PDF loading process, and <code>task.promise</code> resolves when PDF.js has successfully opened the document.</p>
<p>The resulting document object provides access to the PDF's pages and metadata. The application stores this document for later operations, including measuring pages, extracting text, rendering previews, and generating the storyboard.</p>
<h2 id="heading-measuring-pdf-pages">Measuring PDF Pages</h2>
<p>Before arranging pages into storyboard panels, the application needs to know their dimensions.</p>
<p>PDF documents can contain pages with different sizes and orientations. Measuring each page helps the layout engine fit it correctly inside its panel.</p>
<p>The actual application uses the <code>pageFacts()</code> function to measure every page and periodically update the interface while processing large PDFs.</p>
<pre><code class="language-javascript">async function pageFacts(doc, token) {
    var sizes = [];

    for (var n = 1; n &lt;= doc.numPages; n++) {
        if (token !== state.loadToken) {
            return null;
        }

        if (n % 25 === 0) {
            setStatus(
                'Measuring pages: ' + n + ' of ' + doc.numPages + '…',
                true
            );
            await nextFrame();
        }

        var p = await doc.getPage(n);
        var vp = p.getViewport({ scale: 1 });

        sizes.push([vp.width, vp.height]);
    }

    return sizes;
}
</code></pre>
<p>The function starts by creating an empty <code>sizes</code> array. It then loops through all pages using <code>doc.numPages</code> and retrieves each page with <code>doc.getPage(n)</code>.</p>
<p>The <code>getViewport({ scale: 1 })</code> method measures the page at its original scale. The function stores the resulting width and height in the <code>sizes</code> array.</p>
<p>The <code>token</code> parameter helps prevent an outdated loading operation from continuing. If the current token no longer matches <code>state.loadToken</code>, the function stops and returns <code>null</code>.</p>
<p>For larger PDFs, the application updates the loading status after every 25 pages and calls <code>nextFrame()</code> to give the browser an opportunity to update the interface.</p>
<p>Finally, the function returns the array containing the dimensions of all measured pages. These measurements are used later by the storyboard layout calculations.</p>
<h2 id="heading-rendering-pdf-pages-on-canvas">Rendering PDF Pages on Canvas</h2>
<p>The next task is displaying the PDF pages in the workspace.</p>
<p>PDF.js can render an individual page onto an HTML canvas. The canvas provides a visual representation that can be used in the page cards and storyboard preview.</p>
<p>The core rendering function looks like this:</p>
<pre><code class="language-javascript">async function renderPage(n, w, h) {
    var page = await state.doc.getPage(n);
    var b = page.getViewport({ scale: 1 });

    var vp = page.getViewport({
        scale: Math.min(w / b.width, h / b.height)
    });

    var c = document.createElement('canvas');
    c.width = Math.max(1, Math.round(vp.width));
    c.height = Math.max(1, Math.round(vp.height));

    var g = c.getContext('2d');
    g.fillStyle = '#FFFFFF';
    g.fillRect(0, 0, c.width, c.height);

    await page.render({
        canvas: c,
        canvasContext: g,
        viewport: vp
    }).promise;

    return c;
}
</code></pre>
<p>The function accepts three parameters: <code>n</code> is the PDF page number, while <code>w</code> and <code>h</code> define the available width and height for the preview.</p>
<p>First, <code>state.doc.getPage(n)</code> retrieves the requested PDF page. The function then creates a viewport at scale 1 to obtain the page's original dimensions.</p>
<p>Next, <code>Math.min(w / b.width, h / b.height)</code> calculates a scale that fits the page inside the available space without changing its proportions.</p>
<p>The function creates an HTML canvas and sets its width and height using the calculated viewport dimensions. It fills the canvas with white before rendering the PDF page.</p>
<p>Finally, <code>page.render()</code> draws the page onto the canvas. The function waits for rendering to finish and returns the completed canvas for use in the page previews and storyboard.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/fb6abec4-c11f-44e7-b91e-730afd066723.png" alt="PDF Storyboard Generator displaying three PDF page previews rendered on canvas, including text and graphics from the original document." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-reusing-rendered-page-previews">Reusing Rendered Page Previews</h2>
<p>Rendering the same PDF page repeatedly can consume unnecessary processing time. For example, a page might be rendered once for its card preview and again when the storyboard preview is updated.</p>
<p>The application uses a page-picture cache to reuse previously rendered canvases.</p>
<pre><code class="language-javascript">var picCache = new Map();

// For the preview: reuse a page picture when one at least as big is already made.
async function cachedPic(n, w, h) {
    var got = picCache.get(n);

    if (got &amp;&amp; got.w &gt;= w * 0.92) {
        picCache.delete(n);
        picCache.set(n, got);
        return got.c;
    }

    var c = await renderPage(
        n,
        Math.ceil(w * 1.15),
        Math.ceil(h * 1.15)
    );

    picCache.set(n, { c: c, w: c.width });

    while (picCache.size &gt; 60) {
        var old = picCache.keys().next().value;
        picCache.get(old).c.width = 1;
        picCache.delete(old);
    }

    return c;
}
</code></pre>
<p>The application stores rendered page previews in a JavaScript <code>Map</code> called <code>picCache</code>. Each entry contains the rendered canvas and its width.</p>
<p>When <code>cachedPic()</code> is called, it first checks whether a cached image exists for the requested page. If the cached image is at least 92% of the requested width, the application reuses it instead of rendering the page again.</p>
<p>The function moves a reused entry to the end of the Map. This helps the application keep recently used previews available.</p>
<p>If a suitable cached image isn't available, the function calls <code>renderPage()</code> to create a new canvas. It renders the page at 1.15 times the requested width and height, providing some extra resolution for the preview.</p>
<p>To control memory usage, the cache is limited to 60 entries. When that limit is exceeded, the oldest entry is removed, and its canvas width is reduced to 1 to release its drawing resources.</p>
<p>This caching approach avoids unnecessary PDF rendering while keeping memory usage under control, especially when users work with longer documents.</p>
<h2 id="heading-reading-text-from-pdf-pages">Reading Text from PDF Pages</h2>
<p>The storyboard generator can create captions in three ways:</p>
<ol>
<li>The user writes captions manually.</li>
<li>The application extracts text from the PDF.</li>
<li>OCR reads text from scanned pages.</li>
</ol>
<p>For PDFs containing selectable text, PDF.js provides the <code>getTextContent()</code> method.</p>
<p>The actual application uses the <code>readTexts()</code> function to extract and store text from every page in the loaded PDF.</p>
<pre><code class="language-javascript">async function readTexts(token) {
    var doc = state.doc, out = [];

    for (var n = 1; n &lt;= doc.numPages; n++) {
        if (token !== state.loadToken) {
            return;
        }

        try {
            var tc = await (await doc.getPage(n)).getTextContent();

            out.push(tc.items.map(function (it) {
                return (it.str || '') + (it.hasEOL ? '\n' : '');
            }).join(''));
        } catch (e) {
            out.push('');
        }

        if (n % 20 === 0) {
            await nextFrame();
        }
    }

    if (token !== state.loadToken) {
        return;
    }

    state.texts = out;
    refreshTags(board());
}
</code></pre>
<p>The function starts by accessing the loaded PDF document through <code>state.doc</code> and creating an empty array called <code>out</code> to store the extracted text.</p>
<p>It then loops through every page and calls <code>getTextContent()</code> to retrieve its text items. The <code>map()</code> method combines each item's text into a single string. It also adds a newline when the PDF.js item indicates the end of a line through <code>hasEOL</code>.</p>
<p>If text extraction fails for a page, the function adds an empty string to the results instead of stopping the entire process.</p>
<p>The <code>token</code> check prevents an older PDF-loading operation from updating the current application state. The function also calls <code>nextFrame()</code> after every 20 pages to give the browser an opportunity to update the interface.</p>
<p>After processing all pages, the extracted text is stored in <code>state.texts</code>. The application then calls <code>refreshTags(board())</code> to update the page information displayed in the workspace.</p>
<p>This stored text is used later when users choose to fill empty captions automatically.</p>
<h2 id="heading-filling-empty-captions-automatically">Filling Empty Captions Automatically</h2>
<p>Once the application has extracted text from the PDF pages, it can use that text to create captions.</p>
<p>The important behaviour is that the application fills only empty caption fields. It doesn't overwrite captions that users have already entered.</p>
<p>The application uses the <code>captionFromText()</code> helper to clean and shorten the extracted text:</p>
<pre><code class="language-javascript">function captionFromText(t) {
    var s = String(t || '')
        .replace(/\s+/g, ' ')
        .trim();

    if (letters(s) &lt; 3) {
        return '';
    }

    if (s.length &lt;= 200) {
        return s;
    }

    var cut = s.slice(0, 200);
    var end = Math.max(
        cut.lastIndexOf('. '),
        cut.lastIndexOf('? '),
        cut.lastIndexOf('! '),
        cut.lastIndexOf('। ')
    );

    return end &gt; 60
        ? cut.slice(0, end + 1)
        : cut.replace(/\s+\S*$/, '') + '…';
}
</code></pre>
<p>Here's what this function does:</p>
<ol>
<li>Converts the supplied value into a string.</li>
<li>Replaces repeated whitespace with single spaces and removes whitespace from the beginning and end.</li>
<li>Checks whether the text contains enough letters to be useful as a caption.</li>
<li>Returns the complete text if it contains no more than 200 characters.</li>
<li>For longer text, tries to end the caption at a sentence boundary. If there isn't a suitable boundary, it removes the incomplete final word and adds an ellipsis.</li>
</ol>
<p>The application then uses <code>fillFromText()</code> to apply the generated captions to the selected storyboard pages.</p>
<pre><code class="language-javascript">function fillFromText() {
    var bd = board(), list = bd.error ? [] : unique(bd.list), filled = 0, scans = 0;

    list.forEach(function (n) {
        if (captionFor(n)) { return; }

        var c = captionFromText(state.texts[n - 1]);

        if (c) {
            state.captions[n] = c;
            filled++;

            var ta = ui.grid.querySelector('[data-cap="' + n + '"]');
            if (ta) { ta.value = c; }
        } else if (isScan(n)) {
            scans++;
        }
    });

    if (!state.opts.captions &amp;&amp; filled) {
        state.opts.captions = true;
        savePrefs();
    }

    redrawSoon(0);

    if (!list.length) {
        toast(bd.error || 'No pages on the board.', 'error');
        return;
    }

    toast(
        filled
            ? plural(filled, 'caption', 'captions') +
              ' filled from the page text. Edit them in the cards below.' +
              (scans
                  ? ' ' + plural(scans, 'scanned page has', 'scanned pages have') +
                    ' no text; use OCR for ' + (scans === 1 ? 'it' : 'them') + '.'
                  : '')
            : scans
                ? 'The empty pages are scans with no text. Use Read with OCR.'
                : 'Every panel already has a caption.'
    );
}
</code></pre>
<p>The <code>fillFromText()</code> function starts by calling <code>board()</code> to get the currently selected storyboard pages. It uses <code>unique()</code> to avoid processing the same page more than once.</p>
<p>For each selected page, <code>captionFor(n)</code> checks whether a caption already exists. If one is present, the function skips that page so the user's existing caption isn't overwritten.</p>
<p>If the caption is empty, the function retrieves the extracted text from <code>state.texts</code> and passes it to <code>captionFromText()</code>. When useful text is available, it saves the generated caption in <code>state.captions</code> and updates the corresponding textarea in the page card.</p>
<p>If a page has no extractable text and is identified as a scan, the function increases the scanned-page counter. Users can process these pages separately using OCR.</p>
<p>Finally, the application enables captions if necessary, saves the updated preferences, and schedules a preview refresh. It also displays a message showing how many captions were filled or whether OCR is needed.</p>
<p>This allows users to generate starting captions automatically while keeping their manually written descriptions intact.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/ded521e8-6e44-42c4-b02f-115683f40ea3.png" alt="PDF Storyboard Generator showing automatically generated captions below PDF page previews." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-updating-the-preview">Updating the Preview</h2>
<p>Whenever a caption or relevant setting changes, the storyboard preview needs to be refreshed.</p>
<p>The application uses a small scheduling function to avoid redrawing the preview immediately after every individual change:</p>
<pre><code class="language-javascript">function redrawSoon(ms) {
    clearTimeout(drawTimer);
    drawTimer = setTimeout(
        drawPreview,
        ms === undefined ? 120 : ms
    );
}
</code></pre>
<p>The <code>redrawSoon()</code> function first cancels any previously scheduled preview update using <code>clearTimeout()</code>. It then schedules <code>drawPreview()</code> using <code>setTimeout()</code>.</p>
<p>By default, the application waits 120 milliseconds before refreshing the preview. If another change happens during that time, the previous scheduled redraw is cancelled and a new one is scheduled.</p>
<p>This helps prevent unnecessary repeated rendering when users are typing captions or adjusting settings.</p>
<h3 id="heading-drawing-the-updated-preview">Drawing the Updated Preview</h3>
<p>Once the redraw is scheduled, the <code>drawPreview()</code> function calculates the current storyboard configuration and updates the visible preview canvas.</p>
<p>The following is the actual implementation from the application:</p>
<pre><code class="language-javascript">async function drawPreview() {
    if (!state.doc) { return; }

    var my = ++drawToken, bd = board();
    refreshTags(bd);
    syncPanel();

    if (bd.error) {
        ui.boardMsg.textContent = bd.error;
        ui.sheetPos.textContent = 'No sheets';
        ui.sheetCount.textContent = '';
        root.querySelectorAll('[data-needs-board]').forEach(function (b) {
            b.disabled = true;
        });
        return;
    }

    root.querySelectorAll('[data-needs-board]').forEach(function (b) {
        b.disabled = state.busy;
    });

    var L = bd.L, o = state.opts;
    state.sheet = clamp(state.sheet, 0, L.sheets - 1);

    ui.boardMsg.textContent = L.tight
        ? 'Captions leave little room for the pages. Use fewer caption lines, fewer rows or a smaller text size.'
        : '';

    ui.sheetPos.textContent = 'Sheet ' + (state.sheet + 1) + ' of ' + L.sheets;
    ui.sheetCount.textContent =
        plural(bd.list.length, 'panel', 'panels') + ' on ' +
        plural(L.sheets, 'sheet', 'sheets') + ', ' +
        PAPER_NAMES[o.paper] + ' ' + o.orient;

    q('[data-act="sheet-prev"]').disabled = state.sheet &lt;= 0;
    q('[data-act="sheet-next"]').disabled = state.sheet &gt;= L.sheets - 1;

    ui.sheetWrap.style.aspectRatio = L.W + ' / ' + L.H;

    var cssW = ui.sheetWrap.clientWidth || 600;
    var dpr = Math.min(window.devicePixelRatio || 1, 2);
    var k = cssW * dpr / L.W;

    var off = document.createElement('canvas');
    off.width = Math.round(L.W * k);
    off.height = Math.round(L.H * k);

    var done = await drawSheet(
        off.getContext('2d'),
        o,
        bd.list,
        L,
        state.sheet,
        k,
        'full',
        function (n, w, h) {
            return my === drawToken
                ? cachedPic(n, w, h)
                : Promise.resolve(null);
        }
    );

    if (!done || my !== drawToken) { return; }

    ui.sheet.width = off.width;
    ui.sheet.height = off.height;
    ui.sheet.getContext('2d').drawImage(off, 0, 0);

    off.width = 1;

    var start = state.sheet * L.per;
    var on = bd.list.slice(start, start + L.per);

    ui.sheet.setAttribute(
        'aria-label',
        'Sheet ' + (state.sheet + 1) + ' of ' + L.sheets + ': ' +
        (on.length === 1 ? 'page ' + on[0] : 'pages ' + on.join(', '))
    );

    ui.sheet.setAttribute('data-drawn', String(state.sheet + 1));
}
</code></pre>
<p>The function first checks whether a PDF document is loaded. It then calls <code>board()</code> to retrieve the selected pages and calculate the storyboard layout.</p>
<p>The <code>drawToken</code> value helps prevent an older preview-rendering operation from replacing a newer one. The function also calls <code>refreshTags()</code> and <code>syncPanel()</code> to update the page information and settings panel.</p>
<p>Next, it checks whether the selected board has any errors. If the selection is valid, it calculates the current sheet position and updates the sheet counter, panel count, paper information, and Previous and Next buttons.</p>
<p>The function then calculates the canvas scale using the available preview width and the device pixel ratio. The device pixel ratio is capped at 2 to limit the amount of rendering work.</p>
<p>The <code>drawSheet()</code> function draws the selected storyboard sheet onto a temporary canvas. It receives <code>cachedPic()</code> as a callback so previously rendered PDF page previews can be reused.</p>
<p>After drawing finishes, the function checks whether the operation is still current. If it is, the completed temporary canvas is copied onto the visible preview canvas.</p>
<p>Finally, the temporary canvas is released by reducing its width to 1. The application also updates the preview's accessibility label and records which sheet has been drawn.</p>
<p>This process allows users to see their storyboard changes without downloading a new PDF every time they adjust a caption or setting.</p>
<h2 id="heading-choosing-the-storyboard-layout">Choosing the Storyboard Layout</h2>
<p>The tool supports three layout styles: Grid, Panels with notes, and Film strip. Each layout is designed for a different type of project.</p>
<p>Grid layout arranges PDF pages in rows and columns. It works well for reviewing presentation slides, comic pages, and documents.</p>
<p>Panels with notes provides additional writing space below each page. It's useful for lecture notes, planning, and reviewing visual material.</p>
<p>Film strip arranges pages as a sequence of frames. It's useful for planning videos, reels, and scenes.</p>
<p>The selected layout is stored in the application's state. When users choose a different layout, the application updates the number of columns and rows to provide suitable default settings.</p>
<p>The following excerpt from the actual <code>onField()</code> function handles layout changes:</p>
<pre><code class="language-javascript">if (f === 'layout' &amp;&amp; e.type === 'change') {
    // sensible panel counts for each layout
    if (o.layout === 'notes') {
        o.cols = o.orient === 'landscape' ? 2 : 1;
        o.rows = o.orient === 'landscape' ? 3 : 4;
    }

    if (o.layout === 'strip') {
        o.cols = 4;
        o.rows = o.orient === 'landscape' ? 2 : 4;
    }

    if (o.layout === 'grid') {
        o.cols = o.orient === 'landscape' ? 3 : 2;
        o.rows = o.orient === 'landscape' ? 2 : 3;
    }
}

savePrefs();

if (f === 'cols' || f === 'rows' || f === 'layout') {
    state.sheet = 0;
}

redrawSoon(f === 'gap' ? 60 : 0);
</code></pre>
<p>This code checks which layout the user has selected and adjusts the default column and row counts according to the layout and paper orientation.</p>
<p>For example:</p>
<ul>
<li><strong>Panels with notes:</strong> Uses 2 columns and 3 rows in landscape orientation, or 1 column and 4 rows in portrait orientation.</li>
<li><strong>Film strip:</strong> Uses 4 columns, with 2 rows in landscape orientation or 4 rows in portrait orientation.</li>
<li><strong>Grid:</strong> Uses 3 columns and 2 rows in landscape orientation, or 2 columns and 3 rows in portrait orientation.</li>
</ul>
<p>After updating these values, <code>savePrefs()</code> saves the settings. The application resets the current sheet to the first sheet when the layout changes and calls <code>redrawSoon()</code> to refresh the preview.</p>
<p>Users can still adjust the number of rows and columns manually using the board settings.</p>
<h2 id="heading-controlling-rows-columns-and-paper-size">Controlling Rows, Columns, and Paper Size</h2>
<p>Users can choose between 1 and 6 columns and rows per sheet. This gives them control over how many PDF pages appear together.</p>
<p>The application also supports different paper sizes, including A4, Letter, A3, and a 16:9 slide format. Each format can be displayed in portrait or landscape orientation.</p>
<p>For example, a 3-column and 2-row layout can display six PDF pages on one sheet. A 4-column and 3-row layout can display twelve pages.</p>
<p>The application calculates the number of panels that fit on each sheet by multiplying the selected columns by the selected rows. It then determines how many sheets are needed for all selected pages.</p>
<p>The following function from the actual application calculates the sheet dimensions based on the selected paper size and orientation:</p>
<pre><code class="language-javascript">function sheetSize(o) {
    var p = PAPERS[o.paper] || PAPERS.a4;
    var a = Math.min(p[0], p[1]);
    var b = Math.max(p[0], p[1]);

    return o.orient === 'portrait' ? [a, b] : [b, a];
}
</code></pre>
<p>The <code>PAPERS</code> object contains the dimensions for each supported paper format. The function retrieves the selected dimensions and arranges them according to the chosen orientation.</p>
<p>For portrait orientation, the shorter dimension becomes the width and the longer dimension becomes the height. For landscape orientation, these dimensions are reversed.</p>
<p>The layout calculation then uses the selected rows and columns to determine the number of panels per sheet:</p>
<pre><code class="language-javascript">var per = o.cols * o.rows;
var sheets = Math.max(1, Math.ceil(list.length / per));
</code></pre>
<p>Here, <code>per</code> represents the number of panels on one sheet. The <code>Math.ceil()</code> function rounds up the total number of required sheets so that any remaining pages are placed on an additional sheet.</p>
<p>The layout engine also calculates the available space and positions each panel so that the pages fit within the selected sheet dimensions.</p>
<p>When more pages are selected than can fit on one sheet, the remaining panels are placed on additional sheets.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/6f6ef0dd-5d4b-40db-adfb-265687c4c576.png" alt="PDF Storyboard Generator board settings for choosing layout, columns, rows, paper size, and orientation." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-selecting-pdf-pages-and-their-order">Selecting PDF Pages and Their Order</h2>
<p>Users don't always need every page in the original PDF.</p>
<p>The tool supports using all pages, selecting a page range, or entering a custom page sequence.</p>
<p>For example, a user could enter:</p>
<pre><code class="language-text">1-4, 9, 6
</code></pre>
<p>This creates a storyboard using pages 1, 2, 3, 4, 9, and 6 in that exact order.</p>
<p>The application uses the <code>parseList()</code> function to process the custom page selection and check whether the requested page numbers are valid.</p>
<p>Here is the actual implementation from the application:</p>
<pre><code class="language-javascript">function parseList(text) {
    var t = String(text || '').trim();

    if (!t) {
        return { error: 'Type the pages, for example 1-4, 7, 5.' };
    }

    var out = [], parts = t.split(/[,;\s]+/).filter(Boolean);

    for (var i = 0; i &lt; parts.length; i++) {
        var part = parts[i],
            m = /^(\d+)(?:\s*[-–]\s*(\d*))?$/.exec(part);

        if (!m) {
            return { error: '"' + part + '" isn\'t a page number or range.' };
        }

        var a = parseInt(m[1], 10),
            b = m[2] === undefined
                ? a
                : (m[2] === '' ? state.count : parseInt(m[2], 10));

        if (a &lt; 1) {
            return { error: 'Pages start at 1, so "' + part + '" doesn\'t work.' };
        }

        if (b &lt; a) {
            return { error: '"' + part + '" is backwards. Did you mean ' + b + '-' + a + '?' };
        }

        if (a &gt; state.count) {
            return {
                error: 'Page ' + a + ' is past the end; this PDF has ' +
                    plural(state.count, 'page', 'pages') + '.'
            };
        }

        if (b &gt; state.count) {
            return {
                error: 'Page ' + b + ' is past the end. Type ' + a +
                    '- to go to the last page.'
            };
        }

        for (var n = a; n &lt;= b; n++) {
            out.push(n);
        }
    }

    if (out.length &gt; 500) {
        return { error: 'That\'s ' + out.length + ' panels. Use 500 or fewer.' };
    }

    return { pages: out };
}
</code></pre>
<p>The function first converts the input into a trimmed string. It then splits the selection using commas, semicolons, or spaces.</p>
<p>The regular expression checks whether each entry is a single page number or a page range. For example, <code>3</code> represents page 3, while <code>2-5</code> represents pages 2 through 5.</p>
<p>The function also supports an open-ended range such as <code>4-</code>. In this case, the application uses <code>state.count</code> as the final page number.</p>
<p>Before adding pages to the result, it checks that page numbers start at 1, ranges are in ascending order, and no requested page exceeds the total number of pages in the PDF.</p>
<p>The application also limits custom selections to 500 panels. If the input is valid, the function returns an array of page numbers in the exact order entered by the user.</p>
<p>The <code>panels()</code> function then uses this result when building the storyboard. If the user selects all pages instead of entering a custom list, it returns every page in the original order.</p>
<p>This feature is helpful when creating a storyboard from selected scenes or important slides without including the entire PDF.</p>
<h2 id="heading-adding-panel-labels">Adding Panel Labels</h2>
<p>Panel labels help users identify individual pages when reviewing or discussing a storyboard.</p>
<p>The application supports different label styles, including numbers, scene labels, original PDF page numbers, and no labels.</p>
<p>For example, a storyboard could display:</p>
<ul>
<li>1, 2, 3, 4</li>
<li>Scene 1, Scene 2, Scene 3</li>
<li>Page 5, Page 6, Page 7</li>
</ul>
<p>Users can select their preferred label style from the Panel label setting.</p>
<p>The application uses the <code>labelFor()</code> function to generate the appropriate label for each panel:</p>
<pre><code class="language-javascript">function labelFor(o, idx, n) {
    if (o.label === 'panel') {
        return String(idx + 1);
    }

    if (o.label === 'page') {
        return 'Page ' + n;
    }

    if (o.label === 'scene') {
        return 'Scene ' + (idx + 1);
    }

    return '';
}
</code></pre>
<p>The function accepts three parameters:</p>
<ul>
<li><code>o</code> contains the storyboard settings, including the selected label style.</li>
<li><code>idx</code> represents the panel's position in the selected storyboard sequence. It starts at 0.</li>
<li><code>n</code> represents the original PDF page number.</li>
</ul>
<p>When the user selects the panel number option, <code>idx + 1</code> generates labels such as 1, 2, and 3.</p>
<p>When the user selects the page number option, the function uses <code>n</code> to display the original PDF page number. This is useful when the storyboard contains selected pages in a custom order.</p>
<p>For the scene label option, the function generates labels such as Scene 1, Scene 2, and Scene 3. If the user selects No label, it returns an empty string.</p>
<p>The drawing function uses this result when rendering each panel on the storyboard sheet. This helps users identify individual panels without changing the original PDF pages.</p>
<h2 id="heading-drawing-the-storyboard-sheet">Drawing the Storyboard Sheet</h2>
<p>Once the layout has been calculated, the application draws the storyboard sheet on an HTML canvas.</p>
<p>The drawing process places each selected PDF page inside its calculated panel area. It then adds panel labels and captions according to the user's settings.</p>
<p>The actual application uses the asynchronous <code>drawSheet()</code> function for this process. The following excerpt shows how it prepares the sheet and selects the pages that belong on it:</p>
<pre><code class="language-javascript">async function drawSheet(ctx, o, list, L, sheetIdx, k, mode, getPic) {
    var C = COLORS[o.colors] || COLORS.paper;
    var W = L.W * k;
    var H = L.H * k;
    var token = state.loadToken;
    var drawn = [];

    ctx.save();
    ctx.fillStyle = C.bg;
    ctx.fillRect(0, 0, W, H);
    ctx.textBaseline = 'alphabetic';

    var start = sheetIdx * L.per;
    var items = list.slice(start, start + L.per);
</code></pre>
<p>The function receives the canvas context, storyboard settings, selected page list, calculated layout, sheet index, and rendering scale.</p>
<p>It first selects the sheet colors and paints the background. The <code>start</code> variable determines the first panel on the current sheet, while <code>items</code> contains the PDF pages assigned to that sheet.</p>
<p>The following excerpt shows how the application fits each PDF page inside its panel and retrieves its rendered image:</p>
<pre><code class="language-javascript">for (var i = 0; i &lt; items.length; i++) {
    var cell = L.cells[i], n = items[i], idx = start + i;
    var area = cell.img;
    var strip = o.layout === 'strip';

    if (strip) {
        ctx.fillStyle = C.bandMat;
        ctx.fillRect(
            area.x * k, area.y * k,
            area.w * k, area.h * k
        );
    } else if (o.frame) {
        ctx.fillStyle = C.mat;
        ctx.fillRect(
            area.x * k, area.y * k,
            area.w * k, area.h * k
        );
    }

    var inset = strip ? 0 :
        o.frame ? Math.min(area.w, area.h) * 0.04 : 0;

    var pr = fitPage(n, area, inset);

    var px = {
        x: Math.round(pr.x * k),
        y: Math.round(pr.y * k),
        w: Math.max(1, Math.round(pr.w * k)),
        h: Math.max(1, Math.round(pr.h * k))
    };

    drawn.push({ n: n, rect: pr });

    if (mode === 'overlay') {
        ctx.clearRect(px.x, px.y, px.w, px.h);
    } else {
        ctx.fillStyle = '#FFFFFF';
        ctx.fillRect(px.x, px.y, px.w, px.h);

        var pic = getPic ? await getPic(n, px.w, px.h) : null;

        if (token !== state.loadToken) {
            ctx.restore();
            return null;
        }

        if (pic) {
            ctx.drawImage(pic, px.x, px.y, px.w, px.h);
        }
    }
}
</code></pre>
<p>The <code>fitPage()</code> function calculates the position and dimensions needed to fit the original PDF page inside the panel without changing its proportions.</p>
<p>The application then uses <code>getPic()</code> to retrieve the rendered page image. If the image is available, <code>drawImage()</code> places it on the storyboard canvas.</p>
<p>The function also supports an overlay mode, which leaves the page picture areas transparent. This is useful when exporting PDFs while preserving the original PDF page content.</p>
<h3 id="heading-drawing-panel-labels-and-captions">Drawing Panel Labels and Captions</h3>
<p>After positioning the page previews, the application draws the panel labels and captions.</p>
<p>The following excerpt from the actual <code>drawSheet()</code> function shows how panel labels and captions are drawn on the canvas:</p>
<pre><code class="language-javascript">var t = cell.text;
var fs = cell.fs * k;
var lh = cell.lh * k;
var y = t.y * k + fs;

var label = labelFor(o, idx, n);
ctx.textAlign = 'left';

if (label) {
    ctx.font = '700 ' + fs + 'px ' + FONTS.mono;
    ctx.fillStyle = C.ink;
    ctx.fillText(label, t.x * k, y);
    y += lh * 1.05;
}

var lines = [];

if (o.captions &amp;&amp; captionFor(n)) {
    ctx.font = '400 ' + fs + 'px ' + FONTS[o.font];
    ctx.fillStyle = C.ink;

    var maxL = cell.notes
        ? Math.max(1, Math.floor(
            (t.y * k + t.h * k - y + lh - fs) / lh
        ))
        : o.lines;

    lines = wrap(
        ctx,
        captionFor(n),
        t.w * k,
        Math.min(maxL, cell.notes ? 40 : o.lines)
    );

    lines.forEach(function (ln, j) {
        ctx.fillText(ln, t.x * k, y + j * lh);
    });
}
</code></pre>
<p>The <code>labelFor()</code> function generates the selected panel label. The application then uses <code>fillText()</code> to draw it on the canvas.</p>
<p>If captions are enabled and a caption exists, the application uses <code>captionFor()</code> to retrieve it. The <code>wrap()</code> function breaks the caption into lines that fit within the available panel space.</p>
<p>For the Panels with notes layout, the application also draws ruled lines below the caption area. This provides additional writing space for users.</p>
<p>The drawing process combines the original PDF page previews with the labels, captions, frames, and other selected settings to create the completed storyboard sheet.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/4acf38c9-c401-4e11-86d9-cdf62bb67912.png" alt=" Live PDF storyboard preview showing multiple page panels arranged on an A4 landscape sheet." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-updating-the-live-preview">Updating the Live Preview</h2>
<p>One of the most useful features is the live preview. Users can change the layout, paper size, orientation, captions, font, spacing, and other settings without creating a new PDF every time.</p>
<p>The application uses the <code>board()</code> function to calculate the current storyboard configuration before drawing the preview.</p>
<p>Here's the actual implementation:</p>
<pre><code class="language-javascript">function board() {
    var sel = panels();

    if (sel.error) {
        return { error: sel.error };
    }

    var L = layout(state.opts, sel.pages);

    return {
        list: sel.pages,
        L: L
    };
}
</code></pre>
<p>The function first calls <code>panels()</code> to retrieve the selected PDF pages. If the selection contains an error, it returns that error instead of continuing.</p>
<p>Next, it calls <code>layout()</code> with the current storyboard settings and selected pages. The layout function calculates how the pages should be arranged on the storyboard sheets.</p>
<p>Finally, <code>board()</code> returns an object containing the selected page list and the calculated layout. The <code>drawPreview()</code> function uses this information to render the selected sheet onto a temporary canvas.</p>
<p>Once drawing is complete, the result is copied to the visible preview canvas. The application also updates the sheet counter, such as <code>Sheet 1 of 3</code>, and enables or disables the Previous and Next buttons depending on the current position.</p>
<p>This allows users to move between storyboard sheets and review their changes before downloading the result.</p>
<h2 id="heading-adjusting-caption-appearance">Adjusting Caption Appearance</h2>
<p>Captions help explain what's happening on each page.</p>
<p>The application provides options for enabling captions, selecting a font, changing text size, and controlling the number of caption lines.</p>
<p>Users can also choose whether to display panel frames and sheet numbers.</p>
<p>These settings are stored in <code>state.opts</code>. The <code>syncPanel()</code> function updates the settings controls to match the current application state.</p>
<p>Here's the actual implementation:</p>
<pre><code class="language-javascript">function syncPanel() {
    var o = state.opts;

    ['layout', 'cols', 'rows', 'paper', 'orient', 'label',
     'lines', 'tsize', 'font', 'colors'].forEach(function (f) {
        q('[data-field="' + f + '"]').value = String(o[f]);
    });

    q('[data-field="captions"]').checked = o.captions;
    q('[data-field="frame"]').checked = o.frame;
    q('[data-field="numbers"]').checked = o.numbers;

    q('[data-field="gap"]').value = String(o.gap);
    q('[data-out="gap-val"]').textContent = o.gap + ' mm';

    q('[data-field="pages"]').value = state.pages;

    if (document.activeElement !== q('[data-field="title"]')) {
        q('[data-field="title"]').value = state.title;
    }

    var strip = o.layout === 'strip';

    q('[data-out="cols-label"]').textContent =
        strip ? 'Frames per strip' : 'Columns';

    q('[data-out="rows-label"]').textContent =
        strip ? 'Strips per sheet' : 'Rows';

    q('[data-field="lines"]').disabled =
        !o.captions || o.layout === 'notes';

    q('[data-field="frame"]').disabled = strip;

    ui.listWrap.hidden = state.pages !== 'list';
}
</code></pre>
<p>The function reads the current options from <code>state.opts</code> and updates the corresponding controls. For example, it sets the selected font, text size, caption line count, and paper settings.</p>
<p>It also handles layout-specific controls. In Film strip mode, the columns and rows labels change to Frames per strip and Strips per sheet. The caption-line control is disabled when captions are turned off or when the Panels with notes layout is selected.</p>
<h3 id="heading-fitting-captions-inside-panels">Fitting Captions Inside Panels</h3>
<p>Long captions need to fit inside the available panel space. The application uses a <code>wrap()</code> helper to divide text into lines based on the available canvas width.</p>
<p>Here's how the actual drawing code uses that helper:</p>
<pre><code class="language-javascript">if (o.captions &amp;&amp; captionFor(n)) {
    ctx.font = '400 ' + fs + 'px ' + FONTS[o.font];
    ctx.fillStyle = C.ink;

    var maxL = cell.notes
        ? Math.max(1, Math.floor(
            (t.y * k + t.h * k - y + lh - fs) / lh
        ))
        : o.lines;

    lines = wrap(
        ctx,
        captionFor(n),
        t.w * k,
        Math.min(maxL, cell.notes ? 40 : o.lines)
    );

    lines.forEach(function (ln, j) {
        ctx.fillText(ln, t.x * k, y + j * lh);
    });
}
</code></pre>
<p>The application selects the font using <code>FONTS[o.font]</code> and calculates the available number of caption lines based on the panel layout.</p>
<p>For regular layouts, the selected <code>o.lines</code> setting controls the maximum number of lines. For Panels with notes, the available space determines how many lines can be displayed.</p>
<p>The <code>wrap()</code> function breaks the caption into lines that fit the available width. The <code>fillText()</code> method then draws each line onto the canvas.</p>
<p>When there isn't enough space for the selected caption settings, the preview displays a warning suggesting fewer caption lines, fewer rows, or a smaller text size.</p>
<p>The application also supports panel frames and sheet numbers. These options are stored in the application state and applied when the storyboard is drawn.</p>
<p>This gives users control over the appearance and readability of their storyboard captions without changing the original PDF.</p>
<h2 id="heading-navigating-between-storyboard-sheets">Navigating Between Storyboard Sheets</h2>
<p>A large PDF may require several storyboard sheets.</p>
<p>The application provides Previous and Next controls so users can review each sheet individually. It also displays the current sheet number and the total number of sheets.</p>
<p>The selected sheet is stored in <code>state.sheet</code>. The application uses this value to determine which storyboard sheet should be displayed.</p>
<h3 id="heading-handling-the-previous-and-next-buttons">Handling the Previous and Next Buttons</h3>
<p>The application handles sheet navigation inside its main click event listener. Here's the actual implementation:</p>
<pre><code class="language-javascript">case 'sheet-prev':
    if (state.sheet &gt; 0) {
        state.sheet--;
        drawPreview();
    }
    break;

case 'sheet-next':
    state.sheet++;
    drawPreview();
    break;
</code></pre>
<p>When the user clicks Previous, the application checks whether the current sheet number is greater than zero. If it is, <code>state.sheet</code> is decreased by one and <code>drawPreview()</code> refreshes the displayed sheet.</p>
<p>When the user clicks Next, the sheet number is increased and the preview is refreshed.</p>
<p>The application also prevents users from moving beyond the available sheets. Inside <code>drawPreview()</code>, it checks the current sheet position and disables the navigation buttons when necessary:</p>
<pre><code class="language-javascript">state.sheet = clamp(state.sheet, 0, L.sheets - 1);

ui.sheetPos.textContent =
    'Sheet ' + (state.sheet + 1) + ' of ' + L.sheets;

q('[data-act="sheet-prev"]').disabled = state.sheet &lt;= 0;
q('[data-act="sheet-next"]').disabled =
    state.sheet &gt;= L.sheets - 1;
</code></pre>
<p>The <code>clamp()</code> function keeps the selected sheet within the valid range. The sheet counter displays the current position, starting from 1, and the total number of sheets.</p>
<p>The Previous button is disabled on the first sheet, while the Next button is disabled on the last sheet. This makes it easier to review large documents without displaying every storyboard sheet at once.</p>
<h2 id="heading-reading-scanned-pages-with-ocr">Reading Scanned Pages with OCR</h2>
<p>Some PDF documents contain selectable text, while others contain scanned images of printed pages.</p>
<p>PDF.js can extract text from pages containing actual text data. But it can't directly extract words from a scanned page that contains only an image.</p>
<p>To handle these pages, the application provides an optional OCR feature using Tesseract.js.</p>
<p>When users select Read scanned pages with OCR, the application identifies scanned pages that don't already have captions and processes them using the OCR engine.</p>
<h3 id="heading-loading-tesseractjs-when-needed">Loading Tesseract.js When Needed</h3>
<p>The application loads Tesseract.js only when the user requests OCR. It first checks whether the library is already available and reuses an existing loading promise if the script is still being loaded.</p>
<p>Here's the actual <code>loadTesseract()</code> implementation:</p>
<pre><code class="language-javascript">var tessPromise = null;

function loadTesseract() {
    if (window.Tesseract) {
        return Promise.resolve(window.Tesseract);
    }

    if (tessPromise) {
        return tessPromise;
    }

    tessPromise = new Promise(function (resolve, reject) {
        var s = document.createElement('script');
        s.src = TESS + 'tesseract.min.js';
        s.async = true;

        s.onload = function () {
            if (window.Tesseract) {
                resolve(window.Tesseract);
            } else {
                tessPromise = null;
                reject(new Error('engine'));
            }
        };

        s.onerror = function () {
            tessPromise = null;
            reject(new Error('engine'));
        };

        document.head.appendChild(s);

        setTimeout(function () {
            reject(new Error('engine'));
        }, 45000);
    });

    return tessPromise;
}
</code></pre>
<p>The function checks <code>window.Tesseract</code> to see whether the OCR library is already available. If it is, the function returns it immediately.</p>
<p>If the library is still loading, the existing <code>tessPromise</code> is returned instead of creating another script request.</p>
<p>Otherwise, the application creates a script element, sets its source to the Tesseract.js library, and adds it to the document. The <code>onload</code> and <code>onerror</code> handlers detect whether loading succeeds or fails.</p>
<h3 id="heading-creating-the-ocr-worker">Creating the OCR Worker</h3>
<p>After the library loads, the application creates a Tesseract worker configured for English text recognition.</p>
<p>The following excerpt comes from the actual <code>runOcr()</code> function:</p>
<pre><code class="language-javascript">var T = await loadTesseract();
checkCancel();

var w = await T.createWorker('eng', 1, {
    workerPath: TESS + 'worker.min.js',
    corePath: TESS_CORE,
    logger: function (m) {
        if (!m || token !== state.loadToken || !state.busy) {
            return;
        }

        if (/loading language/i.test(m.status)) {
            setProgress(
                m.progress || 0,
                'Getting the English language data (first time only)…'
            );
        } else if (/recogniz/i.test(m.status)) {
            setProgress(
                (done + (m.progress || 0)) / list.length,
                'Reading page ' + list[done] +
                ' (' + (done + 1) + ' of ' + list.length + ')…'
            );
        }
    }
});

state.worker = w;
checkCancel();

await w.setParameters({ debug_file: '/dev/null' });
</code></pre>
<p>The <code>createWorker()</code> method initializes the OCR engine with the English language data. The worker and core paths tell Tesseract.js where to load its supporting files.</p>
<p>The logger reports language-loading and text-recognition progress. The application uses this information to update its progress indicator while OCR is running.</p>
<h3 id="heading-recognizing-text-from-scanned-pages">Recognizing Text from Scanned Pages</h3>
<p>The application processes each eligible scanned page individually. It renders the page at a higher resolution before sending it to Tesseract.js.</p>
<p>Here's the actual page-processing excerpt from <code>runOcr()</code>:</p>
<pre><code class="language-javascript">for (; done &lt; list.length; done++) {
    checkCancel();

    var n = list[done],
        page = await state.doc.getPage(n),
        b = page.getViewport({ scale: 1 });

    var c = await renderPage(
        n,
        Math.min(b.width * 300 / 72, 2600),
        Math.min(b.height * 300 / 72, 2600)
    );

    checkCancel();

    var png = await pngBytes(c);
    c.width = 1;

    var res = await w.recognize(png);

    checkCancel();

    if (token !== state.loadToken) {
        return;
    }

    var cap = captionFromText(res.data &amp;&amp; res.data.text);

    if (cap &amp;&amp; !captionFor(n)) {
        state.captions[n] = cap;

        var ta = ui.grid.querySelector('[data-cap="' + n + '"]');

        if (ta) {
            ta.value = cap;
        }
    }
}
</code></pre>
<p>The function retrieves each scanned PDF page and calculates its original dimensions. It then renders the page at approximately 300 DPI, with a maximum dimension of 2,600 pixels.</p>
<p>The <code>pngBytes()</code> helper converts the rendered canvas into PNG image data. Tesseract.js receives this data through <code>w.recognize(png)</code> and returns the recognized text.</p>
<p>The application passes the recognized text to <code>captionFromText()</code> to clean and shorten it. If the result is useful and the page still has no caption, the application saves it in <code>state.captions</code> and updates the corresponding caption field.</p>
<p>The application also checks for cancellation and verifies that the PDF-loading operation is still current before updating the results.</p>
<p>After processing, the application displays a message asking users to review the generated captions. OCR isn't guaranteed to recognize every word correctly. Image quality, handwriting, unusual fonts, and page orientation can affect the result.</p>
<p>Users should review generated captions before downloading the storyboard.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/100aaec2-33a2-440a-956e-79d078692589.png" alt="PDF Storyboard Generator showing the OCR option for extracting text from scanned PDF pages." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-generating-the-final-storyboard-pdf">Generating the Final Storyboard PDF</h2>
<p>Once the user is satisfied with the layout and captions, the application can generate the final PDF.</p>
<p>This process uses PDF-lib to create a new PDF document. The application creates one output page for each storyboard sheet. It then places the original PDF pages inside their calculated panel positions and adds the storyboard's titles, labels, and captions.</p>
<h3 id="heading-creating-the-pdf-document">Creating the PDF Document</h3>
<p>The actual application uses the <code>exportPdf()</code> function to generate the storyboard. It first creates a new PDF document and checks whether the original PDF pages can be embedded as vector content.</p>
<p>Here's the first part of the actual implementation:</p>
<pre><code class="language-javascript">async function exportPdf(snap, token) {
    await engine();

    var PL = window.PDFLib,
        L = snap.L,
        o = snap.o,
        list = snap.list;

    var out = await PL.PDFDocument.create(),
        src = null,
        embedded = {};

    if (state.vector) {
        try {
            src = await PL.PDFDocument.load(
                state.bytes.slice(0),
                { updateMetadata: false }
            );
        } catch (e) {
            src = null;
        }
    }

    var k = exportScale(L, 300, 14e6);

    for (var s = 0; s &lt; L.sheets; s++) {
        checkCancel();

        if (token !== state.loadToken) {
            return;
        }

        setProgress(
            s / L.sheets,
            'Making sheet ' + (s + 1) + ' of ' + L.sheets + '…'
        );

        var page = out.addPage([L.W, L.H]);
        var c = document.createElement('canvas');

        c.width = Math.round(L.W * k);
        c.height = Math.round(L.H * k);

        var drawn = await drawSheet(
            c.getContext('2d'),
            o,
            list,
            L,
            s,
            k,
            'overlay',
            null
        );

        if (!drawn) {
            return;
        }
</code></pre>
<p>The function first waits for the required PDF libraries using <code>engine()</code>. It then creates a new PDF document with <code>PDFDocument.create()</code>.</p>
<p>The <code>snap</code> parameter contains a snapshot of the selected layout, options, and page list. The application uses these values so the export follows the settings selected by the user.</p>
<p>The <code>state.vector</code> check determines whether the original PDF can be loaded through PDF-lib for vector embedding. The application also calculates a rendering scale targeting 300 DPI, subject to a maximum pixel limit.</p>
<p>The loop creates one output PDF page for every storyboard sheet. It also calls <code>drawSheet()</code> in <code>overlay</code> mode to prepare the titles, panel labels, and captions that will be placed over the original PDF pages.</p>
<h3 id="heading-preserving-original-pdf-pages">Preserving Original PDF Pages</h3>
<p>When vector embedding is available, the application embeds the original PDF pages rather than converting them into ordinary images.</p>
<p>The following excerpt shows how it handles each selected panel:</p>
<pre><code class="language-javascript">for (var i = 0; i &lt; drawn.length; i++) {
    checkCancel();

    var d = drawn[i],
        r = d.rect,
        yb = L.H - r.y - r.h;

    page.drawRectangle({
        x: r.x,
        y: yb,
        width: r.w,
        height: r.h,
        color: PL.rgb(1, 1, 1)
    });

    if (src) {
        var sp = src.getPage(d.n - 1);

        if (!embedded[d.n]) {
            var cb = sp.getCropBox();

            embedded[d.n] = await out.embedPage(sp, {
                left: cb.x,
                bottom: cb.y,
                right: cb.x + cb.width,
                top: cb.y + cb.height
            });
        }

        var em = embedded[d.n],
            rot = ((sp.getRotation().angle % 360) + 360) % 360;

        var turned = rot === 90 || rot === 270,
            sx = r.w / (turned ? em.height : em.width);

        var ew = em.width * sx,
            eh = em.height * sx,
            at = { x: r.x, y: yb };

        if (rot === 90) {
            at = { x: r.x, y: yb + ew };
        } else if (rot === 180) {
            at = { x: r.x + ew, y: yb + eh };
        } else if (rot === 270) {
            at = { x: r.x + eh, y: yb };
        }

        page.drawPage(em, {
            x: at.x,
            y: at.y,
            width: ew,
            height: eh,
            rotate: PL.degrees(-rot)
        });
    }
</code></pre>
<p>The application retrieves the original PDF page using its page number. It then uses <code>embedPage()</code> to embed that page into the new PDF document.</p>
<p>The <code>embedded</code> object caches embedded pages so the same original page doesn't need to be embedded repeatedly.</p>
<p>The code also checks the original page rotation and adjusts its position and dimensions before drawing it. This helps preserve the correct orientation when placing pages inside storyboard panels.</p>
<h3 id="heading-handling-protected-pdfs">Handling Protected PDFs</h3>
<p>If the original PDF can't be embedded as vector content, the application uses a raster fallback.</p>
<p>Here's the actual fallback code:</p>
<pre><code class="language-javascript">else {
    var pic = await renderPage(
        d.n,
        r.w * k,
        r.h * k
    );

    var jpg = await new Promise(function (res) {
        pic.toBlob(function (b) {
            b.arrayBuffer().then(function (a) {
                res(new Uint8Array(a));
            });
        }, 'image/jpeg', 0.92);
    });

    pic.width = 1;

    page.drawImage(
        await out.embedJpg(jpg),
        {
            x: r.x,
            y: yb,
            width: r.w,
            height: r.h
        }
    );
}
</code></pre>
<p>In this case, the application renders the original PDF page onto a canvas and converts it into JPEG image data. PDF-lib then embeds the image inside the corresponding storyboard panel.</p>
<p>This fallback is used when vector embedding is unavailable, including protected PDFs that can't follow the normal vector workflow.</p>
<h3 id="heading-adding-captions-and-saving-the-pdf">Adding Captions and Saving the PDF</h3>
<p>After the original page images or vector content have been placed, the application adds the storyboard's titles, labels, captions, and other drawing elements as an overlay.</p>
<p>The following excerpt shows how the overlay is added and the final PDF is saved:</p>
<pre><code class="language-javascript">var over = await out.embedPng(await pngBytes(c));
c.width = 1;

page.drawImage(over, {
    x: 0,
    y: 0,
    width: L.W,
    height: L.H
});

await nextFrame();
</code></pre>
<p>After all sheets have been processed, the application checks for cancellation and prepares the final PDF:</p>
<pre><code class="language-javascript">checkCancel();

setProgress(1, 'Saving the PDF…');

out.setTitle(state.title || state.base + ' storyboard');
out.setCreator('AllInOneTools PDF Storyboard');
out.setProducer('AllInOneTools (pdf-lib)');

var bytes = await out.save();

if (token !== state.loadToken) {
    return;
}

save(
    new Blob([bytes], { type: 'application/pdf' }),
    state.base + '-storyboard.pdf'
);

toast(
    'Saved ' + plural(L.sheets, 'sheet', 'sheets') +
    ' as ' + state.base + '-storyboard.pdf.'
);
</code></pre>
<p>The <code>embedPng()</code> method adds the storyboard overlay to the PDF page. This overlay contains the titles, panel labels, captions, and other visual elements.</p>
<p>The application then sets the PDF metadata, saves the document as bytes, and creates a downloadable PDF file.</p>
<p>Progress updates and cancellation checks are used throughout the export process, which is particularly helpful when generating storyboards with multiple sheets.</p>
<p>The final PDF combines the original PDF pages with the storyboard layout and captions, ready to download, share, or print.</p>
<h2 id="heading-downloading-png-storyboard-sheets">Downloading PNG Storyboard Sheets</h2>
<p>Users who don't need a PDF can choose PNG sheets.</p>
<p>The application renders each complete storyboard sheet as a PNG image at 200 DPI. If the storyboard contains only one sheet, the browser downloads a single PNG file. If it contains multiple sheets, the application packages them into a ZIP archive.</p>
<h3 id="heading-exporting-the-storyboard-as-png">Exporting the Storyboard as PNG</h3>
<p>The application handles PNG exports inside the <code>exportJob()</code> function. It first calculates the rendering scale and then processes each storyboard sheet.</p>
<p>The following excerpt shows the actual PNG export implementation:</p>
<pre><code class="language-javascript">var k = exportScale(L, 200, 16e6),
    files = [];

for (var s = 0; s &lt; L.sheets; s++) {
    checkCancel();

    setProgress(
        s / L.sheets,
        'Drawing sheet ' + (s + 1) + ' of ' + L.sheets + '…'
    );

    var c = document.createElement('canvas');

    c.width = Math.round(L.W * k);
    c.height = Math.round(L.H * k);

    var ok = await drawSheet(
        c.getContext('2d'),
        o,
        list,
        L,
        s,
        k,
        'full',
        function (n, w, h) {
            checkCancel();
            return renderPage(n, w, h);
        }
    );

    if (!ok) { return; }

    files.push({
        name: state.base + '-storyboard-sheet-' +
            pad2(s + 1) + '.png',
        data: await pngBytes(c)
    });

    c.width = 1;
}

if (files.length === 1) {
    save(
        new Blob([files[0].data], { type: 'image/png' }),
        state.base + '-storyboard.png'
    );
} else {
    save(makeZip(files), state.base + '-storyboard-sheets.zip');
}

toast(
    files.length === 1
        ? 'Saved the storyboard as a PNG.'
        : 'Saved ' + files.length + ' sheets as PNG files in a ZIP.'
);
</code></pre>
<p>The application uses <code>exportScale()</code> to calculate a suitable rendering scale for 200 DPI while keeping the canvas within a maximum pixel limit of 16 million pixels.</p>
<p>For every sheet, it creates a canvas and calls <code>drawSheet()</code> in <code>full</code> mode. This draws the PDF page previews together with the storyboard titles, labels, captions, and other selected settings.</p>
<p>The <code>pngBytes()</code> helper converts the completed canvas into PNG data. Each image is added to the <code>files</code> array with a filename containing its sheet number.</p>
<p>After processing all sheets, the application checks how many PNG files were generated. A single sheet is downloaded directly as a PNG. Multiple sheets are packaged into a ZIP archive using <code>makeZip()</code>.</p>
<p>This format is useful for sharing storyboard previews in presentations, messages, and other applications.</p>
<h2 id="heading-downloading-individual-page-pictures">Downloading Individual Page Pictures</h2>
<p>The third export option is Page pictures (ZIP).</p>
<p>Unlike the PNG sheets option, this export contains individual pictures of the PDF pages selected for the storyboard.</p>
<p>The application renders each selected page separately and places the resulting PNG files into a ZIP archive.</p>
<h3 id="heading-exporting-individual-pdf-pages">Exporting Individual PDF Pages</h3>
<p>The actual application handles this option inside the <code>exportJob()</code> function. It first creates a unique list of selected pages and then renders each page individually.</p>
<p>Here's the actual implementation:</p>
<pre><code class="language-javascript">var pages = unique(list),
    out = [];

for (var i = 0; i &lt; pages.length; i++) {
    checkCancel();

    setProgress(
        i / pages.length,
        'Saving page ' + pages[i] +
        ' (' + (i + 1) + ' of ' + pages.length + ')…'
    );

    var pg = await state.doc.getPage(pages[i]),
        vb = pg.getViewport({ scale: 1 }),
        sc = Math.min(
            2,
            Math.sqrt(12e6 / (vb.width * vb.height))
        );

    var pc = await renderPage(
        pages[i],
        vb.width * sc,
        vb.height * sc
    );

    out.push({
        name: 'panel-' +
            pad2(list.indexOf(pages[i]) + 1) +
            '-page-' + pad2(pages[i]) + '.png',
        data: await pngBytes(pc)
    });

    pc.width = 1;
}

save(makeZip(out), state.base + '-panels.zip');

toast(
    'Saved ' +
    plural(out.length, 'page picture', 'page pictures') +
    ' in a ZIP.'
);
</code></pre>
<p>The function first calls <code>unique()</code> to remove duplicate page numbers from the selected list.</p>
<p>It then processes each page individually. The <code>getPage()</code> method retrieves the original PDF page, and <code>getViewport()</code> obtains its dimensions.</p>
<p>The scale calculation limits the rendering scale to 2 while keeping the rendered page within approximately 12 million pixels. This helps control memory usage when processing large pages.</p>
<p>The <code>renderPage()</code> function creates the page image, while <code>pngBytes()</code> converts the canvas into PNG data.</p>
<p>Each image is added to the <code>out</code> array with a filename containing both its panel position and original PDF page number. This makes it easier to identify the pictures and maintain their storyboard order.</p>
<p>Finally, <code>makeZip()</code> packages all the generated PNG images into a ZIP archive, which the browser downloads.</p>
<p>This option is useful when users want to work with individual PDF page pictures rather than complete storyboard sheets.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/895e4a25-0a30-4402-a728-d4a51fb97b38.png" alt="Board settings and preview, including the PDF, PNG sheets, and Page pictures download buttons." style="display: block;" width="600" height="400" loading="lazy">

<img src="https://cdn.hashnode.com/uploads/covers/6979d22f93bc273cc33971b1/bacaaf21-ffb9-476d-abca-9b0a0d8dc537.png" alt="Exported storyboard PDF opened in a PDF viewer." style="display: block;" width="600" height="400" loading="lazy">

<h2 id="heading-performance-and-important-considerations">Performance and Important Considerations</h2>
<p>Rendering large PDFs and generating high-resolution images can consume significant browser memory.</p>
<p>The application uses page-preview caching, temporary canvases, progress reporting, and cancellation controls to manage this work.</p>
<p>For better results, use fewer panels per sheet when working with large documents. A3 paper can also provide more room when a storyboard contains many panels.</p>
<p>Remember that layout preferences are remembered on the device, but the PDF and captions remain in the current browser tab. Download your work before closing the tab.</p>
<h2 id="heading-demo-pdf-storyboard-generator">Demo: PDF Storyboard Generator</h2>
<p>You can try the finished application here:</p>
<p><a href="https://allinonetools.net/pdf-storyboard-generator/?utm_source=chatgpt.com">PDF Storyboard Generator – AllInOneTools</a></p>
<p>Upload a PDF, arrange its pages, add captions, customize the storyboard, and download the finished result.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Building a PDF Storyboard Generator combines several useful browser technologies into one application.</p>
<p>PDF.js handles PDF loading and page rendering. Tesseract.js provides optional text recognition for scanned pages. PDF-lib creates the final storyboard PDF, while HTML canvas handles previews and image exports.</p>
<p>By connecting these components with JavaScript, we can create a practical tool for organizing presentation slides, comic pages, scripts, and other PDF documents.</p>
<p>The project also demonstrates how browser-based applications can process documents locally without requiring users to upload their files to a server.</p>
<p>With the complete workflow in place, users can turn ordinary PDF pages into organized storyboard sheets that are easier to review, print, and share.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Find and Fix Common Technical SEO Issues on Your Website ]]>
                </title>
                <description>
                    <![CDATA[ Let's say you've built a website. You've invested in the design, bought a domain, and so on. But a website isn't only what you see on the screen. A lot happens behind the scenes. You have to understan ]]>
                </description>
                <link>https://www.freecodecamp.org/news/fix-common-technical-seo-issues/</link>
                <guid isPermaLink="false">6aea2f4db1deb69c0283692a</guid>
                
                    <category>
                        <![CDATA[ SEO ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Saar Twito ]]>
                </dc:creator>
                <pubDate>Tue, 03 Nov 2026 19:00:29 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/8d158690-136a-44a2-aa34-e24be77e004c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Let's say you've built a website. You've invested in the design, bought a domain, and so on. But a website isn't only what you see on the screen. A lot happens behind the scenes. You have to understand how the internet works, as well as how Search Engine Optimization (SEO) works.</p>
<p>Speed is a key part of it, too. A slow site can have very weak SEO, because most people won't spend much time waiting for a page to load, especially these days.</p>
<p>Site speed is a well-known topic with many problems of its own to consider, like Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and server speed. But I'll leave those for another article.</p>
<p>This one is about the problems that stop search engines from reaching and reading your pages.</p>
<p>In my opinion, technical SEO is much harder to apply than regular SEO, which focuses on content and keywords. The technical side usually requires a developer's knowledge, and might need some changes that can feel a bit uncomfortable if you don't have a technical background.</p>
<p>A technical problem can stay unnoticed for months, because you usually don't see it. It's not a design problem. You only find it when you run specific checks, for example with <a href="https://pagespeed.web.dev/">Google PageSpeed Insights</a>.</p>
<p>In this tutorial, you'll find and fix the most common ones on a small practice site. I didn't want to take a real website and shame its owners, so I built a practice site with the problems already in it.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><a href="#heading-prerequisites">Prerequisites</a></li>
<li><a href="#heading-what-is-technical-seo">What Is Technical SEO?</a></li>
<li><a href="#heading-how-common-are-these-problems-on-real-websites">How Common Are These Problems on Real Websites?</a></li>
<li><a href="#heading-how-to-set-up-the-practice-site">How to Set Up the Practice Site</a></li>
<li><a href="#heading-how-to-check-a-pages-http-status-code">How to Check a Page's HTTP Status Code</a><ul>
<li><a href="#heading-what-is-a-soft-404">What Is a Soft 404?</a></li>
</ul>
</li>
<li><a href="#heading-how-to-find-and-fix-redirect-chains">How to Find and Fix Redirect Chains</a></li>
<li><a href="#heading-how-to-make-sure-robotstxt-isnt-blocking-important-pages">How to Make Sure robots.txt Isn't Blocking Important Pages</a></li>
<li><a href="#heading-how-to-find-an-accidental-noindex">How to Find an Accidental noindex</a><ul>
<li><a href="#heading-how-to-check-the-robots-meta-tag">How to Check the Robots Meta Tag</a></li>
<li><a href="#heading-how-to-check-the-x-robots-tag-header">How to Check the X-Robots-Tag Header</a></li>
</ul>
</li>
<li><a href="#heading-how-to-use-canonical-tags-correctly">How to Use Canonical Tags Correctly</a></li>
<li><a href="#heading-how-to-fix-missing-and-duplicate-titles-and-meta-descriptions">How to Fix Missing and Duplicate Titles and Meta Descriptions</a></li>
<li><a href="#heading-how-to-make-your-links-crawlable">How to Make Your Links Crawlable</a></li>
<li><a href="#heading-how-to-check-whether-your-content-needs-javascript-to-appear">How to Check Whether Your Content Needs JavaScript to Appear</a></li>
<li><a href="#heading-can-you-check-a-page-in-five-minutes">Can You Check a Page in Five Minutes?</a></li>
<li><a href="#heading-conclusion">Conclusion</a></li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>You don't need to be an experienced programmer to follow along. You'll need:</p>
<ul>
<li>A web browser, such as Chrome, Firefox, Edge or Safari. In Safari, first turn on <strong>Show features for web developers</strong> under Settings &gt; Advanced.</li>
<li>A terminal: Terminal on macOS, PowerShell on Windows, or any terminal on Linux.</li>
<li><code>curl</code>, a small program that downloads web pages. It comes with macOS, most Linux distributions, and Windows 10 (version 1803 and later) and Windows 11.</li>
<li><a href="https://nodejs.org/">Node.js</a>, to run the practice site. The code was tested with Node.js 26.8 and curl 8.7.</li>
</ul>
<p>On Windows PowerShell, type <code>curl.exe</code> instead of <code>curl</code>, because there <code>curl</code> is a shortcut to a <a href="https://learn.microsoft.com/en-us/windows/curl/">different command</a>. Replace <code>| grep -i "text"</code> with <code>| Select-String "text"</code>, and <code>/dev/null</code> with <code>NUL</code>.</p>
<h2 id="heading-what-is-technical-seo">What Is Technical SEO?</h2>
<p>Google has programs called crawlers. They search the internet all the time for new websites and new pages. When Google discovers a new address, it may crawl the page and process what's on it (the text, images, and videos).</p>
<p>If Google decides the page is worth indexing, it may add it to a very big database of web pages, called the index. Google can then consider the pages in its index for its search results, when they're relevant to what someone searches for. Google's guide to <a href="https://developers.google.com/search/docs/fundamentals/how-search-works">how Search works</a> calls these three steps crawling, indexing, and serving.</p>
<p>So crawling doesn't guarantee indexing, and indexing doesn't guarantee a place in the results. The same guide says Google doesn't guarantee any of the three stages, even for a page that follows all of its rules.</p>
<p>Fixing technical problems won't necessarily make your site rank first on Google. But it does strengthen your chances of ranking higher, because every problem you fix makes your site better.</p>
<p>Technical SEO has to come together with regular SEO, like keywords, backlinks, engagement on social media, and so on.</p>
<h2 id="heading-how-common-are-these-problems-on-real-websites">How Common Are These Problems on Real Websites?</h2>
<p>The numbers below come from audits run with the site-auditing tool I build. Each website counts once, using its first audit, and this data comes from October 25th.</p>
<p>Crawls check many pages on one site (a median of 10 pages here). Single-page audits check one page, usually the home page.</p>
<table>
<thead>
<tr>
<th>Problem</th>
<th>How often</th>
<th>Sample</th>
</tr>
</thead>
<tbody><tr>
<td>At least one page with no canonical tag</td>
<td>64.2% of sites</td>
<td>53 crawled sites, Aug 2025 to Oct 2026</td>
</tr>
<tr>
<td>Two or more pages with exactly the same title</td>
<td>61.8% of sites</td>
<td>34 crawled sites with two or more pages that loaded</td>
</tr>
<tr>
<td>At least one page with no meta description</td>
<td>49.1% of sites</td>
<td>53 crawled sites</td>
</tr>
<tr>
<td>At least one link leading to a page that returns 404</td>
<td>18.9% of sites</td>
<td>53 crawled sites</td>
</tr>
<tr>
<td>Page built mostly with JavaScript</td>
<td>17.7% of pages</td>
<td>277 single-page audits, May to Oct 2026</td>
</tr>
<tr>
<td>At least one page with no title</td>
<td>13.2% of sites</td>
<td>53 crawled sites</td>
</tr>
<tr>
<td>A link that search engines may not be able to follow</td>
<td>8.3% of pages</td>
<td>278 single-page audits</td>
</tr>
<tr>
<td>A robots.txt file with errors, or one that failed to load</td>
<td>7.9% of sites</td>
<td>252 single-page audits, Jul to Oct 2026</td>
</tr>
<tr>
<td>Page blocked by noindex or by robots.txt</td>
<td>4.8% of pages</td>
<td>251 single-page audits, Jul to Oct 2026</td>
</tr>
</tbody></table>
<p>These are all technical problems, but they don't all weigh the same. Missing canonical tags are at the top, but Google doesn't require a canonical tag, so a page without one isn't broken by itself. It matters when the same or very similar content is reachable at more than one URL, as you'll see in the canonical section.</p>
<p>Duplicate titles are something I had myself: when you write code, it's easy to miss things like that. That's why there are tools that check for these problems.</p>
<p>Let's go over each issue in the table to make sure they're all clear:</p>
<ul>
<li><strong>Missing canonical tag:</strong> a canonical tag is basically one of the many tags you put in the <code>&lt;head&gt;</code> of your HTML. When two or three pages have pretty much the same content, it tells search engines like Google which URL is the original, main version, the one you prefer to get indexed. It's not required, though: without it, Google picks the main version itself, so it matters mostly for pages that have duplicates.</li>
<li><strong>Duplicate titles:</strong> it's really easy to end up with the same title on two pages. You don't want a duplicated title because it's not helpful and can confuse Google. Each page should say what it's about.</li>
<li><strong>Missing meta description:</strong> this one is really important, because it helps search engines as well as AI tools like ChatGPT. The meta description is there to explain very briefly what the page is about and what it's for. If you go to Google and search for a website, you'll see it under the actual link to the site.</li>
<li><strong>A link to a 404 page:</strong> this basically means you have a broken link (maybe a link you probably don't use anymore) to a page that isn't there. So there's no reason for it to lead to something that doesn't exist. Use it to lead to something similar, or to something that does exist, so your links remain relevant.</li>
<li><strong>A page built mostly with JavaScript:</strong> Google can run JavaScript, so this alone doesn't keep a page out of Google. But the content appears only after the JavaScript loads and runs, which is slower for visitors and one more step that can fail, and not every crawler runs JS. That's why I prefer <a href="https://www.freecodecamp.org/news/server-side-rendering-in-next-js-for-improved-seo/">server-side rendering</a> for the content that matters most.</li>
<li><strong>A link search engines can't follow:</strong> this isn't a huge deal, and it really depends where the link goes. But say I wrote a really nice article and I want it to help me rank on Google. If search engines can't follow the link to it, then you invested all this time and energy in this article that relatively few people will likely see.</li>
<li><strong>Errors in robots.txt:</strong> robots.txt basically helps you talk to search engines. If there are errors in this file, you might stop search engines from crawling pages you do want in search results.</li>
<li><strong>A page blocked by noindex or robots.txt:</strong> these are two different things. A <code>noindex</code> rule asks search engines to keep a page out of their results, while a robots.txt rule only stops them from crawling it. You'll learn more about both, and why the difference matters, later in this tutorial.</li>
</ul>
<p>Soft 404s, redirect chains, and wrong canonical tags aren't in the table, because the audits don't record them.</p>
<h2 id="heading-how-to-set-up-the-practice-site">How to Set Up the Practice Site</h2>
<p>The practice site is a tiny website for a made-up shoe store called Acme Shoes. Every page on it has one problem built in. You don't need to understand every line of the code.</p>
<p>Create a new folder, add a file called <code>server.js</code>, and paste in this code:</p>
<pre><code class="language-javascript">// server.js: a tiny practice site with common technical SEO problems built in
const http = require('node:http');

const PORT = 8080;
const BASE = 'http://localhost:' + PORT;

// Builds a simple HTML page. Leave out a field to leave that tag out.
function page({ title, description, canonical, robots, body, script }) {
  return [
    '&lt;!doctype html&gt;',
    '&lt;html lang="en"&gt;',
    '&lt;head&gt;',
    '&lt;meta charset="utf-8"&gt;',
    title &amp;&amp; '&lt;title&gt;' + title + '&lt;/title&gt;',
    description &amp;&amp; '&lt;meta name="description" content="' + description + '"&gt;',
    canonical &amp;&amp; '&lt;link rel="canonical" href="' + BASE + canonical + '"&gt;',
    robots &amp;&amp; '&lt;meta name="robots" content="' + robots + '"&gt;',
    '&lt;/head&gt;',
    '&lt;body&gt;',
    body,
    script &amp;&amp; '&lt;script&gt;' + script + '&lt;/script&gt;',
    '&lt;/body&gt;',
    '&lt;/html&gt;',
  ]
    .filter(Boolean)
    .join('\n');
}

const routes = {
  '/': {
    html: page({
      title: 'Acme Shoes: Running Shoes for Every Runner',
      description: 'Lightweight running shoes for road and trail, with free returns.',
      canonical: '/',
      body: [
        '&lt;h1&gt;Acme Shoes&lt;/h1&gt;',
        '&lt;a href="/products/blue-runner"&gt;Blue Runner&lt;/a&gt;',
        '&lt;span onclick="location.href=\'/sale\'"&gt;Summer sale&lt;/span&gt;',
      ].join('\n'),
    }),
  },
  // Problem: a vague title and no meta description
  '/products/blue-runner': {
    html: page({
      title: 'Acme Shoes',
      canonical: '/products/blue-runner',
      body: '&lt;h1&gt;Blue Runner&lt;/h1&gt;',
    }),
  },
  // Problem: a missing product that still answers "200 OK" (a soft 404)
  '/products/red-runner': {
    html: page({
      title: 'Acme Shoes',
      body: '&lt;h1&gt;Sorry, that product could not be found.&lt;/h1&gt;',
    }),
  },
  // Problem: a redirect chain, /old-sale -&gt; /sale-2025 -&gt; /sale
  '/old-sale': { redirect: '/sale-2025' },
  '/sale-2025': { redirect: '/sale' },
  '/sale': {
    html: page({
      title: 'Summer Sale: Up to 40% Off Running Shoes | Acme Shoes',
      description: "Save up to 40% on last season's running shoes until August 31.",
      canonical: '/sale',
      body: '&lt;h1&gt;Summer sale&lt;/h1&gt;',
    }),
  },
  // Problem: a noindex header nobody can see in the page itself
  '/about': {
    headers: { 'X-Robots-Tag': 'noindex' },
    html: page({
      title: 'About Acme Shoes',
      description: 'How a two-person workshop became a running shoe brand.',
      canonical: '/about',
      body: '&lt;h1&gt;About us&lt;/h1&gt;',
    }),
  },
  // Problem: a canonical tag that points to the home page
  '/blog/choosing-trail-shoes': {
    html: page({
      title: 'How to Choose Trail Running Shoes | Acme Shoes',
      description: 'Grip, drop and fit: what to look for in a trail running shoe.',
      canonical: '/',
      body: '&lt;h1&gt;How to choose trail running shoes&lt;/h1&gt;',
    }),
  },
  // Problem: the content only exists after JavaScript runs
  '/catalog': {
    html: page({
      title: 'All Running Shoes | Acme Shoes',
      description: 'Browse every Acme running shoe.',
      canonical: '/catalog',
      body: '&lt;div id="app"&gt;Loading...&lt;/div&gt;',
      script:
        "fetch('/api/products').then((r) =&gt; r.json()).then((products) =&gt; {" +
        "document.getElementById('app').innerHTML = products.map((p) =&gt; '&lt;h2&gt;' + p + '&lt;/h2&gt;').join('');" +
        '});',
    }),
  },
  '/api/products': {
    type: 'application/json',
    html: JSON.stringify(['Blue Runner', 'Trail Grip 2', 'City Glide']),
  },
  // Problem: "Disallow: /blog" blocks every path that starts with /blog
  '/robots.txt': {
    type: 'text/plain',
    html: 'User-agent: *\nDisallow: /blog\n',
  },
};

http
  .createServer((req, res) =&gt; {
    const path = new URL(req.url, BASE).pathname;
    const route = routes[path];

    if (!route) {
      res.writeHead(404, { 'Content-Type': 'text/html; charset=utf-8' });
      return res.end(page({ title: 'Page not found', body: '&lt;h1&gt;Page not found&lt;/h1&gt;' }));
    }
    if (route.redirect) {
      res.writeHead(301, { Location: route.redirect });
      return res.end();
    }
    res.writeHead(200, {
      'Content-Type': (route.type || 'text/html') + '; charset=utf-8',
      ...route.headers,
    });
    res.end(route.html);
  })
  .listen(PORT, () =&gt; console.log('Practice site running at ' + BASE));
</code></pre>
<p>Each key in <code>routes</code> is a page address. The comments that start with <code>Problem:</code> say what's wrong with each page.</p>
<p>Start the server from the same folder:</p>
<pre><code class="language-bash">node server.js
</code></pre>
<p>You should see:</p>
<pre><code class="language-text">Practice site running at http://localhost:8080
</code></pre>
<p>Leave the server running and open a second terminal for the commands below. When you change <code>server.js</code>, stop the server with Ctrl+C and start it again.</p>
<h2 id="heading-how-to-check-a-pages-http-status-code">How to Check a Page's HTTP Status Code</h2>
<p>I remember when I started building websites, I built all kinds of small things. I'm a full stack developer, and I kept trying experiments.</p>
<p>Once I had a problem on the server side and saw in the Network tab that it returned a 500 error. Another time I removed a page on purpose, because I wanted to see if I'd get a 404 or other problems. If you just play around with the site you're building, you'll learn a lot from the results.</p>
<p>HTTP status codes are the first thing a search engine reads. They're the server's way of talking to the client, such as your browser. The codes are split into five ranges: 1xx, 2xx, 3xx, 4xx, and 5xx. A 5xx code is a server problem, for example, and a 4xx code is a client-side problem.</p>
<p>404 is the most common error. It means a page on the site wasn't found. You see 404s all the time, and the fix is typically just to maintain your site and your links.</p>
<p>The codes you'll see in this tutorial are:</p>
<ul>
<li><code>200 OK</code>: here's the page.</li>
<li><code>301 Moved Permanently</code>: the page lives at another address.</li>
<li><code>404 Not Found</code>: there's no page here.</li>
</ul>
<p>Google doesn't index URLs that return a <code>4xx</code> code, according to its documentation on <a href="https://developers.google.com/search/docs/crawling-indexing/http-network-errors">HTTP status codes</a>.</p>
<p>To see the status code of the practice site's home page, use <code>-I</code>, which shows only the headers, and <code>-s</code>, which hides curl's progress meter:</p>
<pre><code class="language-bash">curl -sI http://localhost:8080/
</code></pre>
<pre><code class="language-text">HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sun, 25 Oct 2026 17:42:53 GMT
Connection: keep-alive
Keep-Alive: timeout=5
</code></pre>
<p>Now ask for an address that isn't in <code>routes</code>, to see what a correct 404 looks like:</p>
<pre><code class="language-bash">curl -sI http://localhost:8080/products/does-not-exist
</code></pre>
<pre><code class="language-text">HTTP/1.1 404 Not Found
Content-Type: text/html; charset=utf-8
Date: Sun, 25 Oct 2026 17:42:53 GMT
Connection: keep-alive
Keep-Alive: timeout=5
</code></pre>
<p>In the browser, open the developer tools (F12, or Cmd+Option+I on a Mac), go to the <strong>Network</strong> tab, and reload. The <strong>Status</strong> column shows the code.</p>
<h3 id="heading-what-is-a-soft-404">What Is a Soft 404?</h3>
<p>Check a product the store no longer sells:</p>
<pre><code class="language-bash">curl -sI http://localhost:8080/products/red-runner
</code></pre>
<pre><code class="language-text">HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sun, 25 Oct 2026 17:42:53 GMT
Connection: keep-alive
Keep-Alive: timeout=5
</code></pre>
<p>In the browser, the same page says "Sorry, that product could not be found."</p>
<p>A soft 404 is basically a "page not found", but the server still answers <code>200</code>. It confuses Google, because the address is still there, but what's on it isn't current anymore.</p>
<p>To fix it, make missing pages return a real <code>404</code>, which is what <a href="https://support.google.com/webmasters/answer/7440203">Google recommends</a>. In the practice site, delete the <code>'/products/red-runner'</code> entry from <code>routes</code>. The server then answers <code>404</code>.</p>
<p>Broken links lead to the same dead end. In the data, 18.9% of the 53 crawled sites had at least one link to a page that returned <code>404</code>.</p>
<p>So don't leave links that lead to something that doesn't exist. Update them to lead to something similar, or to something that does exist.</p>
<p>If the page moved, add a <code>301</code> redirect from the old address to the new one. A <code>404</code> is the right answer only for a page that's really gone.</p>
<h2 id="heading-how-to-find-and-fix-redirect-chains">How to Find and Fix Redirect Chains</h2>
<p>A redirect is basically when you want to send one URL (perhaps one that no longer exists) to another URL (that does exist). You might set up a redirect if, for example, you change your domain from <code>example-x.com</code> to <code>example-y.com</code>. You'll want everyone who types <code>example-x.com</code> to be redirected to <code>example-y.com</code> automatically.</p>
<p>Redirects are fine, and they can be quite helpful when used properly. A <code>301</code> means the page moved for good. A <code>302</code> means the move is temporary. Google's documentation on <a href="https://developers.google.com/search/docs/crawling-indexing/301-redirects">redirects</a> explains how it treats each one, and its crawlers <a href="https://developers.google.com/search/docs/crawling-indexing/http-network-errors">follow up to 10 redirect hops</a>.</p>
<p>But a redirect chain happens when an old address, such as a domain you used in the past, redirects to a new one, and then that one redirects again, and again...you get the picture. A few redirects aren't a big deal, but five, six, or seven can be a real problem.</p>
<p>The first command below shows every step of the chain. The second gives you a one-line summary.</p>
<p>Add <code>-L</code> so curl follows the redirects:</p>
<pre><code class="language-bash">curl -sIL http://localhost:8080/old-sale
</code></pre>
<pre><code class="language-text">HTTP/1.1 301 Moved Permanently
Location: /sale-2025
Date: Sun, 25 Oct 2026 17:42:53 GMT
Connection: keep-alive
Keep-Alive: timeout=5

HTTP/1.1 301 Moved Permanently
Location: /sale
Date: Sun, 25 Oct 2026 17:42:53 GMT
Connection: keep-alive
Keep-Alive: timeout=5

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Date: Sun, 25 Oct 2026 17:42:53 GMT
Connection: keep-alive
Keep-Alive: timeout=5
</code></pre>
<p><code>/old-sale</code> goes to <code>/sale-2025</code>, which goes to <code>/sale</code>. For a one-line summary:</p>
<pre><code class="language-bash">curl -sL -o /dev/null -w "%{num_redirects} redirects, ended at %{url_effective}\n" http://localhost:8080/old-sale
</code></pre>
<pre><code class="language-text">2 redirects, ended at http://localhost:8080/sale
</code></pre>
<p><code>-o /dev/null</code> tells curl to write the page's HTML nowhere, so it doesn't fill your terminal and only the summary line is printed. <code>-w</code> sets what that summary line says.</p>
<p>To fix it, point the old/original address straight at the final page:</p>
<pre><code class="language-javascript">'/old-sale': { redirect: '/sale' },
</code></pre>
<p>Restart the server and run the summary again. It now says <code>1 redirects, ended at http://localhost:8080/sale</code>.</p>
<h2 id="heading-how-to-make-sure-robotstxt-isnt-blocking-important-pages">How to Make Sure robots.txt Isn't Blocking Important Pages</h2>
<p>robots.txt is the site's way of telling search engines like Google (and their crawlers) what they're allowed to explore and where they have access.</p>
<p>Look at the practice site's file:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/robots.txt
</code></pre>
<pre><code class="language-text">User-agent: *
Disallow: /blog
</code></pre>
<p><code>Disallow: /blog</code> is dangerous because it stops crawlers from reading every path that starts with <code>/blog</code>. And usually, your articles are what promote your site the most.</p>
<p>Google's <a href="https://developers.google.com/search/docs/crawling-indexing/robots/robots_txt">robots.txt documentation</a> gives the same kind of example: <code>Disallow: /fish</code> also blocks <code>/fish.html</code> and <code>/fishheads</code>.</p>
<p>To fix it, make the rule match only what you meant to block, for example a folder of drafts:</p>
<pre><code class="language-text">User-agent: *
Disallow: /blog-drafts/
</code></pre>
<p>In the practice site, change the <code>html</code> line of the <code>'/robots.txt'</code> entry:</p>
<pre><code class="language-javascript">html: 'User-agent: *\nDisallow: /blog-drafts/\n',
</code></pre>
<p>robots.txt controls crawling, not indexing. Google says it's <a href="https://developers.google.com/search/docs/crawling-indexing/robots/intro">not a mechanism for keeping a page out of Google</a>. For that, you need <code>noindex</code>.</p>
<p>A URL blocked in robots.txt can even appear in search results, usually without a description, if other pages link to it. Google just never reads what's on the page.</p>
<h2 id="heading-how-to-find-an-accidental-noindex">How to Find an Accidental noindex</h2>
<p><code>noindex</code> tells Google not to index a particular page. It's harmful when it ends up on pages you do want indexed and ranked, like a product page or your home page.</p>
<p>But it can be useful on pages you don't need to rank for, or that don't add much to the site, such as log in, sign in, and sign up pages.</p>
<p><code>noindex</code> works only when the crawler can reach the page and read the rule. If robots.txt blocks the same URL, Google never sees the <code>noindex</code>, and the page can still show up in search results. So for a page you want out of Google, use <code>noindex</code> and leave the page crawlable.</p>
<p>In the data, 11 of 457 audited pages (2.4%) had a <code>noindex</code> robots meta tag. There are <a href="https://developers.google.com/search/docs/crawling-indexing/block-indexing">two ways to set it</a>, and you need to check both.</p>
<h3 id="heading-how-to-check-the-robots-meta-tag">How to Check the Robots Meta Tag</h3>
<p>The first way is a tag in the page's <code>&lt;head&gt;</code>:</p>
<pre><code class="language-html">&lt;meta name="robots" content="noindex"&gt;
</code></pre>
<p>Search the page for the word:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/about | grep -i noindex
</code></pre>
<p>On the About page, this prints nothing. You can also right-click the page, choose <strong>View Page Source,</strong> and search for <code>noindex</code>.</p>
<p>Fixing a noindex is really easy. You basically remove it, and then search engines can index the page.</p>
<p>Look for it in the page's code or template, and in your CMS or SEO plugin settings. In WordPress, the setting <strong>Discourage search engines from indexing this site</strong> adds it to every page.</p>
<h3 id="heading-how-to-check-the-x-robots-tag-header">How to Check the X-Robots-Tag Header</h3>
<p>The second way is an HTTP header. Check the About page's headers:</p>
<pre><code class="language-bash">curl -sI http://localhost:8080/about
</code></pre>
<pre><code class="language-text">HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
X-Robots-Tag: noindex
Date: Sun, 25 Oct 2026 17:42:59 GMT
Connection: keep-alive
Keep-Alive: timeout=5
</code></pre>
<p>The header doesn't appear in View Page Source, only in the response headers. In the data, 5 of the 12 blocked pages had no <code>noindex</code> in their HTML: 2 had this header, and 3 were blocked from crawling by robots.txt.</p>
<p>To fix it in the practice site, delete the <code>headers</code> line from the <code>'/about'</code> entry. On a real site, check the server configuration, the hosting provider's header settings, and any SEO plugin.</p>
<h2 id="heading-how-to-use-canonical-tags-correctly">How to Use Canonical Tags Correctly</h2>
<p>If you have several pages that talk about more or less the same thing, but without enough meat to be different, you want to designate one main page. The canonical tag tells search engines which page that is.</p>
<p>The same page can also live at several addresses:</p>
<pre><code class="language-text">https://example.com/blog/choosing-trail-shoes
https://example.com/blog/choosing-trail-shoes?utm_source=newsletter
https://www.example.com/blog/choosing-trail-shoes
</code></pre>
<p>These three addresses show the same article. The first one is the main one: the address you want Google to show in search results. So all three carry the same canonical tag, pointing to that main page:</p>
<pre><code class="language-html">&lt;link rel="canonical" href="https://example.com/blog/choosing-trail-shoes"&gt;
</code></pre>
<p>When Google sees this tag on the <code>?utm_source=newsletter</code> version, it knows that page is a copy of the first address. The main address carries the same tag, pointing to itself. That's called a self-referencing canonical, and it says: I'm the main version.</p>
<p>Google treats it as a <a href="https://developers.google.com/search/docs/crawling-indexing/consolidate-duplicate-urls">strong signal, not a command</a>. If you use canonical tags, a self-referencing one on each main page is a good practice, and Google recommends it.</p>
<p>But you don't have to use canonical tags at all. Google says specifying a canonical isn't required: without one, it picks the version it thinks is best to show users. A canonical tag is a good choice when the same or very similar content is reachable at more than one URL, like the three addresses above.</p>
<p>That's why a missing canonical tag isn't a defect by itself. In the data, 27.1% of 457 audited pages had no canonical tag. What matters is whether any of them have duplicates, like a version with tracking parameters, that need one.</p>
<p>Check the practice site's trail shoe article:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/blog/choosing-trail-shoes | grep -i canonical
</code></pre>
<pre><code class="language-text">&lt;link rel="canonical" href="http://localhost:8080/"&gt;
</code></pre>
<p>The article says its main version is the home page, so Google may show the home page instead of it, or ignore the tag.</p>
<p>The article isn't a copy of anything, so it's its own main version. To fix it, point the article's canonical tag to the article itself:</p>
<pre><code class="language-javascript">canonical: '/blog/choosing-trail-shoes',
</code></pre>
<h2 id="heading-how-to-fix-missing-and-duplicate-titles-and-meta-descriptions">How to Fix Missing and Duplicate Titles and Meta Descriptions</h2>
<p>A good title or meta description is the right length, isn't overloaded, and says briefly what the page is about. It's sort of the essence of the page, like its introduction.</p>
<p>Look at the Blue Runner product page:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/products/blue-runner | grep -i -E "&lt;title&gt;|name=\"description\""
</code></pre>
<pre><code class="language-text">&lt;title&gt;Acme Shoes&lt;/title&gt;
</code></pre>
<p>The title says nothing about the page, and there's no description line at all. In PowerShell, use <code>| Select-String '&lt;title&gt;|name="description"'</code> for this one.</p>
<p>Google's guides to <a href="https://developers.google.com/search/docs/appearance/title-link">titles</a> and <a href="https://developers.google.com/search/docs/appearance/snippet">snippets</a> ask for a unique, descriptive title and description on every page.</p>
<p>To fix it in the practice site, replace the <code>title</code> line of the <code>'/products/blue-runner'</code> entry with:</p>
<pre><code class="language-javascript">title: 'Blue Runner Road Running Shoe | Acme Shoes',
description: 'A lightweight road running shoe with a cushioned sole and free returns.',
</code></pre>
<h2 id="heading-how-to-make-your-links-crawlable">How to Make Your Links Crawlable</h2>
<p>Look at the practice site's home page:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/
</code></pre>
<pre><code class="language-text">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;
&lt;title&gt;Acme Shoes: Running Shoes for Every Runner&lt;/title&gt;
&lt;meta name="description" content="Lightweight running shoes for road and trail, with free returns."&gt;
&lt;link rel="canonical" href="http://localhost:8080/"&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Acme Shoes&lt;/h1&gt;
&lt;a href="/products/blue-runner"&gt;Blue Runner&lt;/a&gt;
&lt;span onclick="location.href='/sale'"&gt;Summer sale&lt;/span&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Everything else on this page is fine: the title, the description, the canonical tag and the Blue Runner link, which is a real <code>&lt;a&gt;</code> element with an <code>href</code>. The only problem is the "Summer sale" <code>&lt;span&gt;</code>.</p>
<p>A <code>&lt;span&gt;</code> is basically HTML that isn't semantic, meaning it has no meaning. A real link does have meaning: search engines can understand it's a link, and screen readers can understand it's a link.</p>
<p>Which links need to be crawlable? Basically, everything you want search engines to see. I mean the products you sell, your articles, your courses, and other things like that.</p>
<p>Google's <a href="https://developers.google.com/search/docs/crawling-indexing/links-crawlable">link guidelines</a> say it can only reliably crawl an <code>&lt;a&gt;</code> element with an <code>href</code>.</p>
<p>To fix it in the practice site, replace the <code>&lt;span&gt;</code> line with:</p>
<pre><code class="language-javascript">'&lt;a href="/sale"&gt;Summer sale&lt;/a&gt;',
</code></pre>
<h2 id="heading-how-to-check-whether-your-content-needs-javascript-to-appear">How to Check Whether Your Content Needs JavaScript to Appear</h2>
<p>With client-side rendering, the JavaScript has to load first, and only then can the other content load.</p>
<p>JavaScript usually builds things like product lists, prices, reviews and menus. Without it, a client-side page often shows only a loading message or an empty box.</p>
<p>Google does render JavaScript, but <a href="https://developers.google.com/search/docs/crawling-indexing/javascript/javascript-seo-basics">in a later phase</a>. The page waits in a rendering queue, which can take a few seconds or longer, and a script that fails or is blocked can leave the rendered page without its content.</p>
<p>That's why server-side rendering is still a good idea, and it's what I prefer for the content that matters. Google's JavaScript guide says the same: server-side rendering makes the site faster for users and crawlers, and not all bots can run JavaScript.</p>
<p>In the data, 17.7% of 277 audited pages were built mostly with JavaScript. That doesn't mean Google couldn't index them, only that their main content depended on JavaScript running correctly.</p>
<p>With server-side rendering, the HTML content comes straight to the browser, and only after that does the JavaScript render.</p>
<p>Google can index pages built either way. Its crawler runs JavaScript with an up-to-date version of Chrome, so server-side rendering isn't a requirement for getting into Google's index.</p>
<p>The next test checks whether the important content is visible without JavaScript. It doesn't show what Google sees, because Google runs the JavaScript, but it shows what every crawler gets before any JavaScript runs.</p>
<p>Open <code>http://localhost:8080/catalog</code> in your browser. You'll see three products. Now download it with curl, which doesn't run JavaScript:</p>
<pre><code class="language-bash">curl -s http://localhost:8080/catalog | grep -i "trail grip"
</code></pre>
<p>This prints nothing, because the product names aren't in the HTML the server sends. Inside <code>&lt;body&gt;</code>, the server only sends:</p>
<pre><code class="language-html">&lt;div id="app"&gt;Loading...&lt;/div&gt;
&lt;script&gt;fetch('/api/products').then((r) =&gt; r.json()).then((products) =&gt; {document.getElementById('app').innerHTML = products.map((p) =&gt; '&lt;h2&gt;' + p + '&lt;/h2&gt;').join('');});&lt;/script&gt;
</code></pre>
<p>Without curl, use <strong>View Page Source</strong> in your browser. On this page, you'll see "Loading..." and the script, but none of the product names, because the browser adds them only after the JavaScript runs.</p>
<p>On your own site, search the source for an important sentence from the page.</p>
<p>To see the page the way Google renders it, use Google's own tools on a live page. On your own site, the URL Inspection tool in Search Console can run a live test (<strong>Test live URL</strong>, then <strong>View tested page</strong>) and show the HTML Google rendered and a screenshot.</p>
<p>For any public page, the <a href="https://search.google.com/test/rich-results">Rich Results Test</a> shows the rendered HTML too. Google <a href="https://developers.google.com/search/docs/crawling-indexing/javascript/fix-search-javascript">recommends both</a> for finding JavaScript problems. Neither can reach <code>localhost</code>, so try them on your real site.</p>
<p>If you want the product names in the HTML from the start, render them on the server. In the practice site, add the product list above <code>routes</code>:</p>
<pre><code class="language-javascript">const products = ['Blue Runner', 'Trail Grip 2', 'City Glide'];
</code></pre>
<p>Replace the catalog's <code>body</code> and <code>script</code> lines with:</p>
<pre><code class="language-javascript">body: '&lt;div id="app"&gt;' + products.map((p) =&gt; '&lt;h2&gt;' + p + '&lt;/h2&gt;').join('') + '&lt;/div&gt;',
</code></pre>
<p>And in the <code>'/api/products'</code> entry:</p>
<pre><code class="language-javascript">html: JSON.stringify(products),
</code></pre>
<p>Restart the server and run the curl command again:</p>
<pre><code class="language-text">&lt;div id="app"&gt;&lt;h2&gt;Blue Runner&lt;/h2&gt;&lt;h2&gt;Trail Grip 2&lt;/h2&gt;&lt;h2&gt;City Glide&lt;/h2&gt;&lt;/div&gt;
</code></pre>
<p>This works because the server now writes the product names into the HTML before it sends the page. Any crawler sees them, even one that can't run JavaScript, and you can still use JavaScript for the interactive parts.</p>
<h2 id="heading-can-you-check-a-page-in-five-minutes">Can You Check a Page in Five Minutes?</h2>
<p>Honestly, it's very hard. There can be a lot of problems, and five minutes isn't enough.</p>
<p>To really know what the problems are, you need to run a full check, for example in Google PageSpeed Insights. If the site is yours, also use the <a href="https://support.google.com/webmasters/answer/9012289">URL Inspection tool</a> in Google Search Console.</p>
<p>The commands from this tutorial are a good start:</p>
<ol>
<li><code>curl -sI</code> for the status code and an <code>X-Robots-Tag</code> header.</li>
<li><code>curl -sIL</code> on an old address to count redirects.</li>
<li><code>/robots.txt</code>, line by line.</li>
<li>View Page Source for <code>noindex</code>, <code>canonical</code>, <code>&lt;title&gt;</code>, <code>description</code> and your important content.</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you fixed eight problems on a practice site: a soft 404, a redirect chain, a robots.txt rule, a hidden <code>noindex</code> header, a wrong canonical tag, a vague title and a missing description, a link crawlers couldn't follow, and content that needed JavaScript.</p>
<p>The most important thing to remember is that you'll need to check your site all the time. Run scans, do maintenance, and make sure nothing breaks, especially when you make improvements or changes to the site.</p>
<p>If you want to go further, my tutorial on <a href="https://www.freecodecamp.org/news/nextjs-json-ld-structured-data/">adding structured data (JSON-LD) to a Next.js site</a> is a good next step.</p>
<p>If you'd like to check a live page for many of these issues in one go, my free tool <a href="https://www.greadme.com/page-audit">Greadme Page Audit</a> tests any URL with no sign-up needed.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Partner with Design Studios on Client Builds: A Freelance Developer's Guide ]]>
                </title>
                <description>
                    <![CDATA[ Let's say a design studio gets a new client project. The branding is ready, the wireframes are approved, the Figma file is polished, and every screen looks pretty much perfect. Then the developer join ]]>
                </description>
                <link>https://www.freecodecamp.org/news/freelance-developer-design-studios/</link>
                <guid isPermaLink="false">6aea10a0338bcff0a27d3b67</guid>
                
                    <category>
                        <![CDATA[ Freelance Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ui/Ux Design ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Collaboration ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reetain Raina ]]>
                </dc:creator>
                <pubDate>Tue, 03 Nov 2026 16:49:36 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/4192997d-6653-4cd6-a51f-22c379b2565c.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Let's say a design studio gets a new client project. The branding is ready, the wireframes are approved, the Figma file is polished, and every screen looks pretty much perfect. Then the developer joins the project. You say, “Here are the designs. Can you build this?”</p>
<p>That sounds simple, until the first question appears. What happens when the mobile version doesn't exist? What if the animation that looks perfect in Figma performs badly on a real phone? Who decides what happens when the client requests Google login three days before launch? And when a technical problem appears, does the developer speak directly to the client or go through the studio?</p>
<p>These questions aren't unimportant side issues. They're part of building the product. Research on designer-developer collaboration supports this. A <a href="https://www.researchgate.net/publication/391931704_Who_is_to_Blame_A_Comprehensive_Review_of_Challenges_and_Opportunities_in_Designer-Developer_Collaboration"><u>2025 systematic review</u></a> covering 45 papers found recurring challenges around how designers and developers communicate, coordinate work, and understand each other's responsibilities.</p>
<p>If you're a freelance developer, your job isn't just about writing code. You also need to make sure that design, technology, scope, communication and client expectations are moving in the same direction.</p>
<p>In this guide, we'll look at how you can work effectively with design studios, from understanding project requirements and handling design handoffs to managing client expectations and technical challenges. We'll also cover some practical ways to make sure projects move smoothly from the initial design to the final launch.</p>
<h3 id="heading-what-well-cover-here">What We'll Cover Here:</h3>
<ul>
<li><a href="#heading-first-understand-what-the-design-studio-is-actually-hiring-you-for">First, Understand What the Design Studio Is Actually Hiring You For</a><ul>
<li><a href="#heading-are-you-the-developer-the-technical-partner-or-just-the-implementer">Are You the Developer, the Technical Partner, or Just the Implementer?</a></li>
</ul>
</li>
<li><a href="#heading-dont-start-coding-until-you-understand-the-project">Don't Start Coding Until You Understand the Project</a><ul>
<li><a href="#heading-ask-questions-before-opening-your-code-editor">Ask Questions Before Opening Your Code Editor</a></li>
</ul>
</li>
<li><a href="#heading-treat-the-figma-file-as-a-conversation-not-a-contract">Treat the Figma File as a Conversation, Not a Contract</a></li>
<li><a href="#heading-define-who-owns-which-decisions">Define Who Owns Which Decisions</a><ul>
<li><a href="#heading-the-one-question-every-freelancer-should-ask">The One Question Every Freelancer Should Ask</a></li>
</ul>
</li>
<li><a href="#heading-set-up-a-workflow-that-doesnt-depend-on-constant-messages">Set Up a Workflow That Doesn't Depend on Constant Messages</a><ul>
<li><a href="#heading-give-every-stage-a-clear-done">Give Every Stage a Clear "Done"</a></li>
<li><a href="#heading-create-a-single-source-of-truth">Create a Single Source of Truth</a></li>
</ul>
</li>
<li><a href="#heading-handle-design-handoffs-like-an-engineer">Handle Design Handoffs Like an Engineer</a><ul>
<li><a href="#heading-look-for-the-screens-that-dont-exist">Look for the Screens That Don't Exist</a></li>
</ul>
</li>
<li><a href="#heading-scope-creep-is-easier-to-prevent-than-to-fight">Scope Creep Is Easier to Prevent Than to Fight</a><ul>
<li><a href="#heading-use-a-simple-change-rule">Use a Simple Change Rule</a></li>
</ul>
</li>
<li><a href="#heading-dont-hide-technical-problems-until-the-deadline">Don't Hide Technical Problems Until the Deadline</a></li>
<li><a href="#heading-review-the-build-together-not-just-at-the-end">Review the Build Together, Not Just at the End</a></li>
<li><a href="#heading-learn-to-push-back-without-becoming-difficult-to-work-with">Learn to Push Back Without Becoming Difficult to Work With</a></li>
<li><a href="#heading-keep-the-relationship-healthy-after-launch">Keep the Relationship Healthy After Launch</a></li>
<li><a href="#heading-a-simple-collaboration-checklist-for-freelance-developers">A Simple Collaboration Checklist for Freelance Developers</a></li>
<li><a href="#heading-final-thoughts">Final Thoughts</a></li>
</ul>
<h2 id="heading-first-understand-what-the-design-studio-is-actually-hiring-you-for">First, Understand What the Design Studio Is Actually Hiring You For</h2>
<p>This is an important section because freelancers often misunderstand their exact role in a project. A design studio or a <a href="https://helmsworkshop.com/"><u>branding agency</u></a> might hire you for frontend development, full-stack development, prototyping, or straight design to code implementation. They might also bring you in for CMS integration, API integration, performance optimization, or ongoing maintenance after launch.</p>
<p>But the role can vary dramatically depending on the studio's internal capabilities and the client's specific needs.</p>
<h3 id="heading-are-you-the-developer-the-technical-partner-or-just-the-implementer">Are You the Developer, the Technical Partner, or Just the Implementer?</h3>
<p>You must explain the difference and define your boundaries.</p>
<p>As an implementer, you simply receive finished designs and build them exactly as specified without questioning the logic. As a developer, you build the product but also actively raise technical concerns when you spot potential issues. As a technical partner, you get involved much earlier in the process and help determine what can actually be built within the budget and timeline.</p>
<p>Clarifying this exact dynamic before starting the work prevents many structural problems later.</p>
<h2 id="heading-dont-start-coding-until-you-understand-the-project">Don't Start Coding Until You Understand the Project</h2>
<p>A Figma file can tell you exactly what something looks like on a screen. It doesn't necessarily tell you how it should behave in the real world.</p>
<p>It won't show you what happens when data is missing from the server. It doesn't explain what happens on slow cellular networks or what happens on obscure mobile devices. It also leaves out what happens when user-generated text becomes too long or when users make critical mistakes. And it doesn't talk about which interactions are absolutely essential, and which parts are merely visual prototypes rather than final requirements.</p>
<h3 id="heading-ask-questions-before-opening-your-code-editor">Ask Questions Before Opening Your Code Editor</h3>
<p>You need a practical checklist to run through before touching your keyboard.</p>
<p>Regarding the product, ask: What problem is the product solving? Who is using it? What's the single most important user action?</p>
<p>Regarding the design, ask: Are these designs entirely final? Are there dedicated mobile and tablet versions available? Are all the shown animations part of the strict requirement?</p>
<p>Regarding the technical side, ask: Is there an existing backend in place? What specific technology stack is expected? Are all necessary APIs already available? Who handles the hosting environment?</p>
<p>Regarding the client, ask: Who communicates directly with the client? Who ultimately approves changes? Who gives you final feedback?</p>
<p><a href="https://getdx.com/blog/site-reliability-engineering/"><u>Google's engineering guidance</u></a> similarly stresses clear objectives and requirements because poor communication and vague expectations directly contribute to project failures</p>
<h2 id="heading-treat-the-figma-file-as-a-conversation-not-a-contract">Treat the Figma File as a Conversation, Not a Contract</h2>
<p>Explain to your partners that developers shouldn't treat design files as sacred objects that must be reproduced pixel for pixel regardless of technical reality. Instead, treat them as a starting point for an ongoing discussion.</p>
<p>For example, a designer creates a complex scrolling animation that looks genuinely great in the initial prototype. But during implementation you discover that it causes massive performance issues on lower-end mobile devices.</p>
<p>The wrong approach is saying something like: "The design says so, so I'll build it anyway." Another wrong approach is shutting it down by saying: "That simply won't work."</p>
<p>A much better approach is saying something along the lines of: "This interaction is entirely possible, but it may affect performance on mobile devices. Could we simplify the animation specifically for smaller screens?" That's constructive technical feedback without turning the conversation into a hostile design vs development argument.</p>
<p>This dynamic is supported by a <a href="https://www.researchgate.net/publication/391931704_Who_is_to_Blame_A_Comprehensive_Review_of_Challenges_and_Opportunities_in_Designer-Developer_Collaboration"><u>comprehensive 2025 systematic review</u></a> of designer-developer collaboration, which revealed that separate decision-making procedures and a lack of mutual understanding are persistent challenges in the field.</p>
<h2 id="heading-define-who-owns-which-decisions">Define Who Owns Which Decisions</h2>
<p>This is especially important when you're a freelancer working directly between a studio and its end client. You need to create a simple, clear responsibility framework. Usually, visual design is led solely by the design studio. UX decisions are generally handled by the design studio alongside the client.</p>
<p>Technical architecture, database structure and API implementation are led exclusively by the developer. Product priorities are decided by the client and the studio. Technical feasibility falls entirely to the developer. Final design approval rests with the client and the studio.</p>
<p>Emphasize that this framework isn't totally rigid. The important thing is universally knowing who has the final say in any given category.</p>
<h3 id="heading-the-one-question-every-freelancer-should-ask">The One Question Every Freelancer Should Ask</h3>
<p>"If we disagree about a design or technical decision, who makes the final call?" That one specific question can save countless hours of confusion and resentment later in the process.</p>
<h2 id="heading-set-up-a-workflow-that-doesnt-depend-on-constant-messages">Set Up a Workflow That Doesn't Depend on Constant Messages</h2>
<p>A simple, predictable workflow eliminates chaos, and you can systematically organize a standard workflow.</p>
<p>First is the brief, followed by the design review. Next comes technical planning and then the actual development phase. After that is the internal review, followed by client feedback. This leads to the revision stage, moving into QA and finally culminating in the launch.</p>
<p>Explaining each phase briefly ensures everyone knows where the project stands at any given moment.</p>
<h3 id="heading-give-every-stage-a-clear-done">Give Every Stage a Clear "Done"</h3>
<p>For example, a design review is officially complete when desktop and mobile designs exist, missing interactive states are identified, visual assets are available, and complex interactions are understood.</p>
<p>The development phase is complete when the feature actually works, responsive behavior is thoroughly checked, known bugs are actively documented, and the studio has a functional review build.</p>
<p>This clarity inherently prevents the classic miscommunication of: "I thought you were still working on it."</p>
<h3 id="heading-create-a-single-source-of-truth">Create a Single Source of Truth</h3>
<p>The core problem with freelance collaborations is that crucial information can become quickly scattered across Slack, email, WhatsApp, Figma comments, GitHub, Notion, Google Docs, random video calls, and text messages. Then six days later someone inevitably asks: "Why did we decide to remove that specific feature?" Nobody likely remembers the exact reason.</p>
<p>Recommend having one centralized place for core requirements, open questions, finalized decisions, technical constraints, scope changes, project deadlines and feedback.</p>
<p>An <a href="https://research.ibm.com/publications/collaboration-information-seeking-and-communication-an-observational-study-of-software-developers-work-practices"><u>observational study</u></a> of software developers' work practices found that developers spend about 45% of their time collaborating with colleagues and seeking information, making information visibility an essential part of software work. <a href="https://getdx.com/blog/site-reliability-engineering/"><u>Google's SRE guidance</u></a> also recommends writing decisions and project information down to heavily reduce problems caused by distance and fragmented communication.</p>
<h2 id="heading-handle-design-handoffs-like-an-engineer">Handle Design Handoffs Like an Engineer</h2>
<p>Instead of simply receiving a Figma link and guessing what to do, create a proper, methodical handoff checklist. Check typography, colors, spacing and breakpoints. Verify all assets, icons, component states and hover states. Confirm loading states, error states and empty states. Double-check mobile behavior, accessibility requirements and complex animations.</p>
<h3 id="heading-look-for-the-screens-that-dont-exist">Look for the Screens That Don't Exist</h3>
<p>Designers naturally often show the happy path where everything works perfectly. But developers absolutely have to build the empty dashboards and the failed API requests. You must account for loading screens, invalid forms, expired sessions, and missing images. You have to handle long usernames breaking the layout and slow connections timing out. This is precisely where developers add tangible value beyond simply translating a Figma canvas into HTML, CSS, and JavaScript.</p>
<h2 id="heading-scope-creep-is-easier-to-prevent-than-to-fight">Scope Creep Is Easier to Prevent Than to Fight</h2>
<p>The studio might initially say: "The client also wants a small dashboard." Then a few days later: "Can we subtly add notifications?" Then the next week: "Could we also seamlessly add Google login?"</p>
<p>None of these requests sound huge individually. But together, they can easily turn a straightforward two week project into an exhausting month-long project.</p>
<h3 id="heading-use-a-simple-change-rule">Use a Simple Change Rule</h3>
<p>Whenever something new appears in the pipeline, ask a series of questions. Is this part of the original scope? How much active work will it require? Does it negatively affect the deadline? Does it conflict with another feature? Who formally approves the change?</p>
<p>Don't make the section sound like aggressive negotiation advice. Frame it entirely as protecting the overall project from unclear expectations and budget overruns.</p>
<h2 id="heading-dont-hide-technical-problems-until-the-deadline">Don't Hide Technical Problems Until the Deadline</h2>
<p>Explain the freelancer's ethical and professional responsibility here. If you discover the API isn't actually ready, state it immediately. If the animation isn't practical, the design doesn't account for accessibility, the database structure needs completely changing, or a feature will take three days instead of three hours, say it early. Not two agonizing days before the scheduled launch. You can introduce a very simple principle: bad news gets significantly more expensive when you delay it.</p>
<h2 id="heading-review-the-build-together-not-just-at-the-end">Review the Build Together, Not Just at the End</h2>
<p>Explain clearly why continuous reviews are infinitely better than one giant final review at the very end of the timeline. A suggested review rhythm keeps everyone in the loop.</p>
<p>After a major component is finished, conduct a studio review. After the main page is completed, run a design review. After responsive implementation is coded, initiate a mobile review. Before the actual launch, perform a full QA.</p>
<p>This creates significantly smaller, highly manageable feedback loops. Instead of hearing: "The entire website is completely wrong," you get: "The spacing on this specific card is 4px too large." This is much easier and cheaper to fix.</p>
<h2 id="heading-learn-to-push-back-without-becoming-difficult-to-work-with">Learn to Push Back Without Becoming Difficult to Work With</h2>
<p>Developers sometimes respond to highly unrealistic requirements with a flat: "That's impossible."</p>
<p>Instead, you should frame it differently: "We can certainly build this, but there are two distinct trade-offs." Then explain the available paths clearly. Option A is visually closer to the design, but requires much more development time. Option B is a much simpler implementation, delivering significantly better performance. Option C is to keep the current approach for desktop interfaces and drastically simplify it on mobile devices.</p>
<p>This directly makes the developer a strategic problem solver rather than someone who simply says yes or no to every request.</p>
<h2 id="heading-keep-the-relationship-healthy-after-launch">Keep the Relationship Healthy After Launch</h2>
<p>The professional relationship shouldn't abruptly end the exact second the site goes live on the server. Clarify the boundaries of the bug-fix period and ongoing maintenance. Discuss future features, hosting responsibilities and comprehensive documentation. Manage the handover of access credentials and establish clear code ownership.</p>
<p>Most importantly, don't ever leave ownership ambiguous. The design studio should confidently know what happens if the client comes back three months later aggressively asking for a brand new feature.</p>
<h2 id="heading-a-simple-collaboration-checklist-for-freelance-developers">A Simple Collaboration Checklist for Freelance Developers</h2>
<p>Before the project officially starts, thoroughly define the core business logic, clarify your exact engineering responsibilities, and audit the UI/UX designs for edge cases or missing interactive states.</p>
<p>Once you understand the primary goals, confirm the complete technology stack, from the frontend framework to the database architecture, while setting strict boundaries around API dependencies, version control repositories, and sprint deadlines.</p>
<p>As you move into active development, consistently flag performance bottlenecks or query inefficiencies early, ensuring you document all major architectural shifts within your codebase. Rather than jumping straight into writing, break down the visual files into reusable component logic and shared design tokens before implementation begins. You should also share live staging builds frequently, track scope creep meticulously through an issue tracker, and continuously test how your DOM renders across various viewport breakpoints to catch responsive errors.</p>
<p>Finally, before pushing to the production environment, audit the compiled build against the original designs to ensure high-fidelity accuracy. Rigorously test state management across critical user routing flows, debug any layout shifts on mobile browsers, and verify that your semantic HTML meets baseline WCAG accessibility standards.</p>
<p>To wrap up the collaboration seamlessly, lock down the CI/CD deployment pipeline responsibilities and hand over a comprehensively documented repository that clearly explains the environmental variables, build scripts, and third-party integrations the studio will need moving forward.</p>
<h2 id="heading-final-thoughts">Final Thoughts</h2>
<p>A Figma file shows how a product should look, while development reveals everything it needs to handle when real people start using it.</p>
<p>That's why working with a design studio involves more than a simple design-to-code handoff. You'll also need to catch technical problems early, keep responsibilities clear, and make decisions before small issues become launch-day problems.</p>
<p>Throughout the project, stay in touch with the design team, share your technical concerns, and discuss changes before they affect the timeline. This will make it easier to handle unexpected problems and deliver a product that works well for the client and the people who will eventually use it.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Make Your Coding Agent Check Its Work in the Browser ]]>
                </title>
                <description>
                    <![CDATA[ I got tired of coding agents telling me the frontend work was done when nobody had opened the frontend. You've probably seen the routine. The agent changes some code, runs the formatter, the type chec ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-make-your-coding-agent-check-its-work-in-the-browser/</link>
                <guid isPermaLink="false">6ad731804f84a96f720e9e9d</guid>
                
                    <category>
                        <![CDATA[ playwright ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Testing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Frontend Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ timothy ogbemudia ]]>
                </dc:creator>
                <pubDate>Tue, 20 Oct 2026 09:16:48 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/cbbc37b8-4405-4aa3-a691-0d7c7301baf2.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>I got tired of coding agents telling me the frontend work was done when nobody had opened the frontend.</p>
<p>You've probably seen the routine. The agent changes some code, runs the formatter, the type checker, and the tests, everything comes back green, and you get some version of "Implemented and verified."</p>
<p>But verified how, exactly? A passing test suite is useful evidence, but it isn't the same as opening the app and using the thing that just changed.</p>
<p>I've had plenty of changes where the code made sense and the tests passed, and the UI still had the kind of problem a person spots in about three seconds. A control overlapping something else. A selected state that exists in the store but isn't highlighted on screen. Reset working for one path and not another. A filter that updates state but leaves the old data on the page. Save looking fine until you refresh. A map layer drawn in the wrong order. A modal that technically opens but doesn't fit on the screen.</p>
<p>The agent had tested its code, but nobody had tested the application. So I started making browser review part of the definition of done for anything user-facing, and a few weeks in, that habit turned into a tool. I'll get to that near the end.</p>
<p>In this article, you'll learn how to give a coding agent a real browser with Playwright MCP, and how to write the instructions that make it test the change it just made instead of confirming that a page loads.</p>
<p>You'll see how to have the agent start your app the way your project already starts it, how to split those instructions between <code>AGENTS.md</code> and a reusable skill, why a separate reviewer agent catches bugs the author misses, and how to make the agent clean up only what it started.</p>
<p>In the last part, I'll walk through katalepsis, the open source tool this turned into, including how it decides whether a check really passed.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-the-loop-agents-are-missing">The Loop Agents Are Missing</a></p>
</li>
<li><p><a href="#heading-why-a-browser-on-its-own-falls-short">Why a Browser on Its Own Falls Short</a></p>
</li>
<li><p><a href="#heading-how-to-start-the-real-app">How to Start the Real App</a></p>
</li>
<li><p><a href="#heading-where-the-instructions-live">Where the Instructions Live</a></p>
</li>
<li><p><a href="#heading-why-the-reviewer-should-work-independently">Why the Reviewer Should Work Independently</a></p>
</li>
<li><p><a href="#heading-clean-up-after-yourself-and-only-yourself">Clean Up After Yourself and Only Yourself</a></p>
</li>
<li><p><a href="#heading-when-a-skill-stopped-being-enough">When a Skill Stopped Being Enough</a></p>
</li>
<li><p><a href="#heading-how-to-try-katalepsis">How to Try katalepsis</a></p>
</li>
<li><p><a href="#heading-how-katalepsis-works-under-the-hood">How katalepsis Works Under the Hood</a></p>
</li>
<li><p><a href="#heading-what-happened-when-i-used-it">What Happened When I Used It</a></p>
</li>
<li><p><a href="#heading-where-i-landed">Where I Landed</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>This isn't a beginner tutorial, so it helps to have:</p>
<ul>
<li><p>Some experience with a coding agent that supports MCP (Model Context Protocol), such as Claude Code, Codex, or Cursor, and an idea of how you give it instructions.</p>
</li>
<li><p>A web app you can run locally with a dev script, written in JavaScript or TypeScript. The examples use a Node project with <code>pnpm</code>, but nothing depends on a specific framework.</p>
</li>
<li><p>Basic Playwright knowledge: what a test, a locator, and an assertion look like. You don't need an existing test suite to follow the first half.</p>
</li>
<li><p>Node.js 20 or newer for Playwright MCP, and Node.js 22.12 or newer plus Git if you want to install katalepsis.</p>
</li>
<li><p>Comfort with the terminal and Git, since the agent will be starting processes and checking <code>git status</code>.</p>
</li>
</ul>
<h2 id="heading-the-loop-agents-are-missing">The Loop Agents Are Missing</h2>
<p>Coding agents got useful quickly in large part because they already have a decent feedback loop for code. They read, edit, and run the formatter and tests, read the failure, and try again. Nobody has to get it right in one heroic attempt.</p>
<p>For frontend work, the clear missing input is the frontend itself. The loop I want goes a bit further: edit the code, run the tests, start the app, use the changed feature, look at what happened, fix whatever's broken, and then use it again.</p>
<p>That last step matters more than you might think. Agents are very comfortable telling you a fix "should now work", and I'd rather they just open the page again and find out.</p>
<p>Playwright MCP is a good way to give them that. I already used Playwright for E2E tests, but the MCP server is useful for a different reason: it hands the agent a browser directly. It can open localhost, read the page, find controls, click and type, check what changed, and take screenshots.</p>
<p>That isn't the same as asking the agent to run <code>pnpm playwright test</code>. The test suite tells you whether the scenarios you already wrote down still pass. Browser review asks what this particular change could have affected and goes to look.</p>
<p>If an agent refactors some shared map-layer utilities, the tests might cover a few helpers. But from the diff, it can also work out that the code runs during initial render, selection, filtering, and reset, and try each of those. That's a lot closer to how I review my own frontend work.</p>
<p>Setup is small. You need Node 20 or newer and an MCP-capable client:</p>
<pre><code class="language-json">{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"]
    }
  }
}
</code></pre>
<p>A quick sanity check is to ask the agent to open the Playwright TodoMVC demo, add a todo called "Browser QA," and confirm it shows up. If it manages that, it has a browser. What it does with one is the harder part.</p>
<h2 id="heading-why-a-browser-on-its-own-falls-short">Why a Browser on Its Own Falls Short</h2>
<p>Giving an agent a browser only gives it the ability to look. It doesn't tell the agent what to look at, how far to go, or what counts as proof, and without that it falls back to the cheapest thing that technically involves a browser. An agent with Playwright can still do hilariously weak QA. I've had reports like this:</p>
<pre><code class="language-text">Opened /route.
Page loaded successfully.
Browser verification complete.
</code></pre>
<p>That's a report about opening a page, not about testing a change. Nothing in it would have caught any of the bugs from the start of this article.</p>
<p>So the browser needed instructions to go with it. What follows are the rules I wrote for how an agent should review its own frontend work: what to test, what to check, and what evidence to bring back. They started as a few lines I kept repeating in prompts, and they later became the browser-review skill you'll see in the next sections.</p>
<p>The first rule I settled on is that the review has to come from the change. If it changed a filter, use the filter. If it changed reset logic, change some state first and then reset it. If it touched persistence, refresh the page. If it changed a modal, open and close the modal, and if it changed responsive layout, resize the viewport.</p>
<p>That all sounds obvious when a person says it, but it isn't obvious at all if your agent instructions just say "verify that the app works".</p>
<p>In practice, this means the agent reads the diff and turns it into a short test plan before it touches the browser. For a change to a filter bar, the plan I'd expect looks something like this:</p>
<pre><code class="language-text">Changed: src/features/projects/FilterBar.tsx, src/features/projects/useFilters.ts

Plan:
1. Open /projects and note how many rows are showing.
2. Filter by Status: Active. Every row should say Active.
3. Add Owner: me on top. The list should narrow again.
4. Clear filters. The original row count should come back.
5. Apply a filter and refresh. The filter lives in the URL, so it should survive.
</code></pre>
<p>Then it carries out that plan through the browser tools Playwright MCP exposes. A trimmed version of the calls for the first few steps looks like this:</p>
<pre><code class="language-text">browser_navigate   { "url": "http://localhost:5173/projects" }
browser_snapshot   {}                      → table with 40 rows
browser_click      { "element": "Status filter", "ref": "e14" }
browser_click      { "element": "Active option", "ref": "e31" }
browser_snapshot   {}                      → table with 12 rows, all "Active"
browser_click      { "element": "Clear filters", "ref": "e15" }
browser_snapshot   {}                      → table with 40 rows
</code></pre>
<p>The <code>ref</code> values come from the accessibility snapshot, which is how the agent finds a control without guessing at CSS selectors.</p>
<p>This paid off on a PR that fixed a cursor getting stuck in its hover state on an interactive map. The PR's new unit tests passed against the old code too, so they didn't prove the fix did anything. What did prove it was the agent opening the app, moving on and off the interactive layers, and watching the cursor change and reset exactly when it should.</p>
<p>The second rule is to check the end result rather than the interaction. "I clicked Reset and nothing threw" doesn't tell you much. What you actually care about is that reset puts things back the way they were. Same with saving: the real claim is that you can change a setting, save, refresh, and it's still there.</p>
<p>Written as a Playwright test, that claim looks like this. The important line is the last one, which runs after the reload:</p>
<pre><code class="language-ts">import { test, expect } from "@playwright/test";

test("weekly digest setting survives a reload", async ({ page }) =&gt; {
  await page.goto("/settings/notifications");
  await page.getByRole("switch", { name: "Weekly digest" }).click();
  await page.getByRole("button", { name: "Save" }).click();

  await page.reload();

  await expect(page.getByRole("switch", { name: "Weekly digest" })).toBeChecked();
});
</code></pre>
<p>The agent doesn't need to write this test to follow the rule. Through MCP it does the same thing by hand: click, save, <code>browser_navigate</code> to the same URL, and read the switch's state from a fresh snapshot.</p>
<p>I also ask for different evidence depending on the question. Whether the URL changed, a button is disabled, or a dialog opened is a question for the DOM and browser state, not a screenshot. Whether that dialog is clipped, two things overlap, or text wraps badly on a phone is a visual question, and that's where screenshots are useful. Sometimes you need both, since a modal can sit happily in the DOM while being unusable on screen.</p>
<p>For a layout change, that means resizing and capturing what a person would actually see:</p>
<pre><code class="language-text">browser_resize            { "width": 375, "height": 812 }
browser_click             { "element": "Export button", "ref": "e22" }
browser_take_screenshot   { "filename": "export-dialog-375.png" }
browser_resize            { "width": 1440, "height": 900 }
browser_take_screenshot   { "filename": "export-dialog-1440.png" }
</code></pre>
<p>While it's in there, the agent may as well look at the console and, when the feature depends on an API call, the network. I only care about errors the change introduced, though. A warning that's been on <code>main</code> for six months shouldn't derail every review, and a client-only transition doesn't need a network audit. If a save that "worked" actually got a <code>500</code>, I want to hear about it.</p>
<p><code>browser_console_messages</code> and <code>browser_network_requests</code> return what the page logged and requested, so a failed save shows up as a line like this even when the UI looked fine:</p>
<pre><code class="language-text">[PUT] http://localhost:5173/api/settings =&gt; [500] Internal Server Error
</code></pre>
<p>Put together, the rules turn the weak report from the start of this section into something I can actually check:</p>
<pre><code class="language-text">Route: /settings/notifications
Did: turned on "Weekly digest", clicked Save, reloaded the page.
Checked: switch still on after reload (aria-checked="true");
  PUT /api/settings returned 200; no new console errors.
Screenshots: settings-375.png, settings-1440.png (label wraps cleanly on mobile)
Tests: pnpm test settings (14 passed)
Found and fixed: Save stayed disabled after the first save. Fixed in
  SettingsForm.tsx, then went through the flow again.
</code></pre>
<h2 id="heading-how-to-start-the-real-app">How to Start the Real App</h2>
<p>The agent can't test anything until the app is running, and this is where it's most tempting for it to take shortcuts.</p>
<p>I didn't want to write "run <code>pnpm dev</code>" into every repository, so the procedure tells the agent to work out how the project starts. It checks the <code>dev</code> script in <code>package.json</code> first, then whatever the README documents, and only falls back to an existing Docker setup if the app can't reasonably run otherwise.</p>
<p>The procedure here is the "Start the application" section of the browser-review skill, which you'll see in full in the next section. In a typical Vite or Next.js project, following it looks something like this:</p>
<pre><code class="language-bash"># 1. How does this project start?
jq .scripts package.json
# {
#   "dev": "vite",
#   "build": "vite build",
#   "test": "vitest run",
#   "e2e": "playwright test"
# }

# 2. Start the dev server in the background, in a temp folder the agent owns,
#    and record the PID so it can stop exactly this process later.
QA_DIR=$(mktemp -d)
pnpm dev --port 5173 &gt; "$QA_DIR/dev.log" 2&gt;&amp;1 &amp;
echo $! &gt; "$QA_DIR/dev.pid"

# 3. Wait until the server answers before opening a browser.
until curl -sf http://localhost:5173 &gt; /dev/null; do sleep 1; done
</code></pre>
<p>If there's no <code>dev</code> script, the README is next, and if the README says the app needs Postgres and Redis from <code>docker compose up</code>, the agent uses that compose file and records the containers it started. It doesn't write a new one.</p>
<p>What I really don't want is the agent changing the app to make it easier to test. No temporary auth bypass, no fake server, no edits to <code>.env</code>, and no throwaway route that exists only because it couldn't work out the real setup. The point is to exercise the software I'm actually shipping.</p>
<p>This is the kind of change I mean, and agents really do reach for it when a login page is in the way:</p>
<pre><code class="language-diff">- if (!session) redirect("/login");
+ if (!session &amp;&amp; process.env.NODE_ENV !== "development") redirect("/login");
</code></pre>
<p>If the agent can't get past authentication with the project's documented test account or seed data, the right move is to stop and report that browser review is blocked and why. A blocked review is honest. A review of an app with its auth switched off isn't a review of my app.</p>
<h2 id="heading-where-the-instructions-live">Where the Instructions Live</h2>
<p>My first instinct was to keep adding to <code>AGENTS.md</code>. It already held the rules every agent in the repo should know: structure, conventions, testing philosophy, keep changes surgical, and no pointless comments.</p>
<p>I was about to add another hundred lines about starting the app, browser setup, what to click, screenshots, console errors and teardown...but at some point that file stops being instructions and turns into a small religious text.</p>
<p>It helps to know how each of these files is actually used. <code>AGENTS.md</code> is a plain Markdown file that coding agents such as Codex read automatically at the start of every session in that repository, and Claude Code does the same with <code>CLAUDE.md</code>. Everything in it lands in the agent's context for every task, whether the task is a CSS fix or a database migration. So it costs context on every run, and it applies everywhere.</p>
<p>A skill works differently. It's a folder with a <code>SKILL.md</code> file that starts with a short <code>name</code> and <code>description</code>. At the start of a session the agent only sees that name and description, a line or two per skill. When a task matches the description, or another instruction points at the skill, the agent reads the rest of the file and follows it. So you can have a long, detailed procedure that costs almost nothing until it's needed.</p>
<p>What I landed on is treating <code>AGENTS.md</code> as the constitution and skills as the playbooks. A constitution is short, applies to everything, and says what must be true without explaining how to do it. A playbook is a step-by-step procedure for one kind of situation, and you only pull it out when you're in that situation.</p>
<p>In this setup, <code>AGENTS.md</code> says that user-visible work isn't done until it's been checked in a browser, and the browser-review skill says how to do the checking:</p>
<pre><code class="language-text">/
├── AGENTS.md
└── .agents/
    └── skills/
        ├── browser-review/
        │   └── SKILL.md
        ├── pr-review/
        │   └── SKILL.md
        └── grill-me/
            └── SKILL.md
</code></pre>
<p>The rule in <code>AGENTS.md</code> stays short and always visible:</p>
<pre><code class="language-md">## Browser Verification

User-visible work is not complete until the affected behavior has been
verified in the running application.

For user-visible changes, follow `.agents/skills/browser-review/SKILL.md`.

A successful build, type check, unit test suite, or E2E test suite does
not replace browser verification.

Do not commit browser-verification artifacts. Stop anything you started
for verification and clean up before hand-off.
</code></pre>
<p>The skill holds the procedure and only gets loaded when it's needed. I use Codex and Claude Code, so there's one global <code>AGENTS.md</code> that Claude's <code>CLAUDE.md</code> imports, and one shared skills folder both of them read. Whichever agent I'm in that day, it follows the same playbook.</p>
<p>The import is a single line, because Claude Code lets <code>CLAUDE.md</code> pull in another file with <code>@</code>:</p>
<pre><code class="language-md">@~/.codex/AGENTS.md
</code></pre>
<p>Here's a shortened version of the one I first wrote:</p>
<pre><code class="language-md">---
name: browser-review
description: Verify user-visible changes in the running application with Playwright MCP.
---

# Browser Review

## Before verification

Run `git status --short` and remember what was already there. Don't touch
pre-existing work.

Read the task and the diff. Work out the affected routes, the changed flow,
the loading, empty, error, selected and disabled states that matter,
whether anything needs to survive a refresh, and what nearby behavior
could regress.

## Start the application

Use the repository's dev script, then its documented local setup, then its
existing Docker setup. Don't invent a new startup config and don't change
app behavior to make QA easier. Record every process and container you start.

## Exercise the change

Don't stop once the page loads. Go through the whole changed flow and check
the final result. Use browser or DOM state for functional claims and
screenshots for visual ones. Report new relevant console errors and failed
requests, not old warnings.

If something is broken, fix the smallest cause, rerun the affected tests
and go through the flow again. Don't assume the fix works.

## Cleanup

Teardown is required even when verification fails. Close browsers, stop
servers and containers, and delete screenshots, traces and other artifacts,
but only the ones you created. Run `git status --short` again before
hand-off. Never run `git add`, `git commit` or `git push`.

## Report

Say which routes you tested, what you did, which states you checked, what
tests you ran and what you found and fixed. If you couldn't finish, say why.
</code></pre>
<p>None of that is clever. The value is that it's the default expectation, so I'm not relying on the agent to decide by itself that it should open a browser.</p>
<h2 id="heading-why-the-reviewer-should-work-independently">Why the Reviewer Should Work Independently</h2>
<p>The clear weakness is that the agent deciding whether the work is done is the same one that wrote it. That's still worth something, since I test my own code too, but it starts with a theory of how its implementation works.</p>
<p>By theory I mean the author's mental model of its own change: which code it touched, what it believes that code affects, and, just as important, what it believes it didn't affect. Its test plan comes straight from that model. So it tests the paths it meant to change, they work, and it never looks at the path it didn't realize was involved. That's the same blind spot people have when they test their own code, and it's exactly where the bugs that survive review tend to live.</p>
<p>So when a second agent reviews a branch, I tell it to work out the test scope for itself. My global rules now require a fresh reviewer with no conversation history: it gets the original request, the diff, and the review skill, and nothing about why the author thinks it works. It decides what the code could affect and tests that, without leaning on the author's screenshots, QA notes, or green test run.</p>
<p>The prompt for that reviewer is short on purpose:</p>
<pre><code class="language-text">You are reviewing a branch you did not write.

Original request:
  Make the E2E app URL configurable through E2E_BASE_URL so the
  tests can run against any port.

Run `git diff main...HEAD` to see the change. Follow the browser-review
skill. Work out for yourself what this change could affect, test that,
and report what you checked with evidence.
</code></pre>
<p>The best catch so far came from a PR that made an end-to-end test setup's app URL configurable. The reviewer noticed the seeded test data still hardcoded image URLs to the old port, and running the app on a different port confirmed it. Three image requests went to the wrong port and failed, and the page quietly rendered fallback cards where the images should have been. Nothing threw.</p>
<p>Simplified, the global setup looked like this after the change:</p>
<pre><code class="language-ts">// e2e/global-setup.ts
const baseURL = process.env.E2E_BASE_URL ?? "http://localhost:8080";

await seedDatabase({
  media: [
    { id: "m1", url: "http://localhost:8080/test-media/cover-1.jpg" },
    { id: "m2", url: "http://localhost:8080/test-media/cover-2.jpg" },
    { id: "m3", url: "http://localhost:8080/test-media/cover-3.jpg" },
  ],
});
</code></pre>
<p>The author's theory was "the app URL now comes from <code>E2E_BASE_URL</code>", and every test it ran used the default port, where the hardcoded URLs happened to be right. The reviewer had no such theory. It read the whole setup file the diff touched, ran the app on port 8081, and came back with this:</p>
<pre><code class="language-text">Found: seeded media URLs in e2e/global-setup.ts still point at :8080.
Ran the app with E2E_BASE_URL=http://localhost:8081.
Network: 3 requests to http://localhost:8080/test-media/... failed
  (net::ERR_CONNECTION_REFUSED).
Screen: the gallery rendered 3 fallback cards instead of images
  (gallery-8081.png).
Suggested fix: build the seeded URLs from E2E_BASE_URL, or make them
  relative.
</code></pre>
<p>The fix was one line per URL:</p>
<pre><code class="language-ts">{ id: "m1", url: new URL("/test-media/cover-1.jpg", baseURL).href },
</code></pre>
<p>A test that checks the cards exist passes either way, because a fallback card is still a card. You only see it by looking at the page and the network tab, which is the whole argument of this article in one bug.</p>
<h2 id="heading-clean-up-after-yourself-and-only-yourself">Clean Up After Yourself and Only Yourself</h2>
<p>Once agents can start servers and browsers, cleanup is part of the design. Otherwise every session leaves a layer behind: a stray node process, a Chromium window, screenshots, a Playwright trace, a temporary auth file, or a Docker container.</p>
<p>"Clean everything" is the wrong fix, though. <code>pkill node</code> isn't cleanup, it's an agent going on a small rampage, and it'll happily kill the dev server you started in another terminal. <code>git clean -fd</code> will delete an untracked file that has nothing to do with the agent.</p>
<p>The rule is to clean up what you created and leave everything else alone, and the <code>git status</code> before and after is there so browser QA doesn't quietly end up in my next commit.</p>
<p>This is why the startup step records a PID in a temp folder. Cleanup can then be precise:</p>
<pre><code class="language-bash"># Not cleanup
pkill node
git clean -fd

# Cleanup
kill "$(cat "$QA_DIR/dev.pid")"
rm -rf "$QA_DIR"
</code></pre>
<p>And this is roughly what I expect to see at the end of a review:</p>
<pre><code class="language-text">Cleanup
- Stopped the dev server I started (pid 48213, pnpm dev --port 5173).
- Closed the Playwright MCP browser.
- Deleted export-dialog-375.png and export-dialog-1440.png.
- Left running: pid 39102 (pnpm dev on :3000). It was already running
  before I started, so it isn't mine.

git status --short before review:
 M src/features/export/ExportDialog.tsx
?? notes/todo.md

git status --short after cleanup:
 M src/features/export/ExportDialog.tsx
?? notes/todo.md
</code></pre>
<p>The two <code>git status</code> blocks match, so nothing from the review leaked into the working tree, and the untracked notes file that was already there is still there.</p>
<p>I didn't make this rule up in the abstract, either. While building the tool I'm about to describe, the agent testing it ran a cleanup command that closed every Playwright browser on my machine, not just its own. To be fair, it owned up to it in its summary.</p>
<h2 id="heading-when-a-skill-stopped-being-enough">When a Skill Stopped Being Enough</h2>
<p>The skill worked, in the sense that agents started actually opening the app. But what I got back was still prose. The agent would tell me it opened the page, clicked through the flow and everything looked right, and I had to take its word for it.</p>
<p>It's the same problem I started with, just one level up. I didn't want a nicer sentence about the browser. I wanted the evidence: what was checked, what passed, what failed, and the screenshots and traces to back it up, in a form I could drop into a PR for whoever reviews it.</p>
<p>So I wrote a build plan and spent a Saturday building it, pairing with Claude Code through milestones and independent review rounds. It's called <a href="https://www.katalepsis.glamboyosa.xyz">katalepsis</a>, the Stoic word for grasping something so clearly you can't be wrong about it, which felt like a fair bar for a pull request.</p>
<p>You point it at a preview URL and it writes a report: HTML, Markdown you can paste into the PR, and a JSON manifest.</p>
<p>It does two things. <code>katalepsis run</code> runs your existing Playwright tests against the preview, and Playwright's result is final. katalepsis sorts, redacts and bundles it, and never reinterprets an assertion.</p>
<p><code>katalepsis verify</code> takes plain-English checks for behavior nobody has written a test for, and a model drives a real browser with your own Anthropic, OpenAI, or OpenRouter key. There's also an MCP server, so the agent that just made a change can run either one itself and read the report back.</p>
<h2 id="heading-how-to-try-katalepsis">How to Try katalepsis</h2>
<p>katalepsis isn't on npm yet, so the installer clones the repository and builds it. It needs Node 22.12 or newer, Git, and pnpm 10 (or corepack, which ships with Node):</p>
<pre><code class="language-bash">curl -fsSL https://www.katalepsis.glamboyosa.xyz/install.sh | sh
</code></pre>
<p>That puts two launchers, <code>katalepsis</code> and <code>katalepsis-mcp</code>, in <code>~/.local/bin</code>.</p>
<p>To run your existing tests against a preview, your Playwright config has to use the URL katalepsis passes in. It's also worth turning on failure evidence so the report has something to show:</p>
<pre><code class="language-ts">// playwright.config.ts
use: {
  baseURL: process.env.KATALEPSIS_BASE_URL ?? "http://localhost:3000",
  screenshot: "only-on-failure",
  video: "retain-on-failure",
  trace: "retain-on-failure",
},
</code></pre>
<p>The repository includes a small demo app, a signup form with a deliberate bug: submitting the empty form does nothing instead of showing an error. It has three Playwright tests. Here's a real run against it:</p>
<pre><code class="language-text">$ katalepsis run --cwd apps/demo-form --url http://127.0.0.1:4173
katalepsis: FAILED
  2 passed, 1 failed, 0 blocked, 0 not tested
  Preview commit: not reported, so unconfirmed
  Report: artifacts/katalepsis/2026-10-19T08-21-25-288Z-3dba5a/report.html
  Markdown: artifacts/katalepsis/2026-10-19T08-21-25-288Z-3dba5a/report.md
</code></pre>
<p>The Markdown report is meant to be pasted into a PR. The top of it looks like this:</p>
<pre><code class="language-md"># katalepsis report: Failed

**2 passed, 1 failed, 0 blocked** out of 3 checks run.

- Preview: http://127.0.0.1:4173/
- Preview commit: not reported, so unconfirmed
- Runner: katalepsis 0.1.0, Playwright 1.63.0, Node 22.22.0

## Checks

| Status | Check | Project | Location | Duration |
| --- | --- | --- | --- | --- |
| Failed | signup form › empty submission shows a required-field error | chromium | signup.spec.ts:8 | 3.2 s |
| Passed | signup form › valid submission shows a confirmation | chromium | signup.spec.ts:13 | 418 ms |
| Passed | signup form › malformed email shows an email error and does not submit | chromium | signup.spec.ts:20 | 449 ms |

### Failed: signup form › empty submission shows a required-field error

- Failure type: assertion
- Evidence: screenshot, video, log, trace
</code></pre>
<p>Below that, it includes Playwright's own failure message (<code>getByRole('alert')</code> never appeared) and a list of limitations, such as the preview not reporting which commit it was built from.</p>
<p>For behavior without a test, you write checks in plain English. Each one has an intent, which is what to do, and a pass condition, which is what must be true at the end:</p>
<pre><code class="language-json">{
  "checks": [
    {
      "id": "empty-form",
      "name": "Empty form validation",
      "intent": "Submit the signup form without filling it",
      "passCondition": "A required-field error is visible"
    },
    {
      "id": "invalid-email",
      "name": "Invalid email",
      "intent": "Fill the name, enter an invalid email address and submit",
      "passCondition": "An email validation error is visible and the success confirmation is not shown"
    }
  ]
}
</code></pre>
<p>Then you give katalepsis a key and run them. The key is stored in your OS keychain or read from an environment variable, and it's never passed on the command line:</p>
<pre><code class="language-text">$ katalepsis auth set openrouter
$ katalepsis verify --cwd apps/demo-form --url http://127.0.0.1:4173 --checks checks.json \
    --provider openrouter --model anthropic/claude-haiku-5.5
katalepsis: FAILED (openrouter/anthropic/claude-haiku-5.5)
  2 passed, 1 failed, 0 blocked
  Preview commit: not reported, so unconfirmed
  Report: artifacts/katalepsis/2026-10-10T12-45-05-343Z-b51a0a/report.html
</code></pre>
<p>The demo's full <code>checks.json</code> has three checks, and the agent checks find the same empty-form bug the Playwright test did, without anyone having written that test.</p>
<p>Finally, so the coding agent can do all of this itself, you register the MCP server. With Codex, that's:</p>
<pre><code class="language-bash">codex mcp add katalepsis -- katalepsis-mcp --root /path/to/your-app
</code></pre>
<p>The server exposes three tools, <code>verification_run_tests</code>, <code>verification_check_browser</code>, and <code>verification_get_report</code>, and only works inside the folder you give it. In practice the agent's instruction becomes something like "after changing the signup form, run <code>verification_check_browser</code> with a check for the change and paste the Markdown report into your summary."</p>
<h2 id="heading-how-katalepsis-works-under-the-hood">How katalepsis Works Under the Hood</h2>
<p>A few of the decisions came straight out of the problems in this article. Here's how they work in the code.</p>
<p>katalepsis is a TypeScript monorepo with five packages:</p>
<ul>
<li><p><code>core</code> (the result schema, the Playwright runner, and the report renderers)</p>
</li>
<li><p><code>agent</code> (the browser tools and evidence rules for <code>verify</code>)</p>
</li>
<li><p><code>credentials</code> (keys and preferences)</p>
</li>
<li><p><code>mcp</code> (the MCP server)</p>
</li>
<li><p><code>cli</code></p>
</li>
</ul>
<p>It uses Effect for the parts where errors, cancellation, and dependencies matter, such as running Playwright and probing the preview, and Effect Schema for the report format. The model loop in <code>verify</code> uses the Vercel AI SDK, so the same code works with Anthropic, OpenAI, and OpenRouter.</p>
<h3 id="heading-the-report-is-a-schema-not-a-log">The Report is a Schema, Not a Log</h3>
<p>Every run, whether it came from Playwright or from a model, decodes into the same <code>VerificationRun</code> structure before anything is written. A trimmed version of a single check looks like this:</p>
<pre><code class="language-ts">export const CheckStatus = Schema.Literals(["passed", "failed", "blocked"]);

export const VerificationCheck = Schema.Struct({
  id: Schema.String,
  source: Schema.Literals(["playwright-test", "agent"]),
  title: Schema.String,
  status: CheckStatus,
  flaky: Schema.Boolean,
  failure: Schema.NullOr(Schema.Struct({ code: FailureCode, message: Schema.String })),
  attempts: Schema.Array(Attempt),
  evidence: Schema.Array(BundlePath),
});
</code></pre>
<p>Tests that never ran go into a separate <code>notTested</code> list with a reason, which is how you end up with four outcomes: passed, failed, blocked, or not tested. Every evidence file is stored with its SHA-256 hash, and <code>BundlePath</code> rejects absolute paths and <code>..</code>, so a report can't point outside its own folder.</p>
<h3 id="heading-blocked-isnt-failed">Blocked isn't Failed</h3>
<p>If the preview is down, you get one blocked run, not three failed tests that send you hunting for bugs that don't exist. Before starting Playwright, katalepsis requests the preview URL once. This is the core of that probe:</p>
<pre><code class="language-ts">const UNAVAILABLE_STATUSES = new Set([502, 503, 504]);

const response = await fetch(url, {
  redirect: "manual",
  signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),
});
if (UNAVAILABLE_STATUSES.has(response.status)) {
  return { reachable: false, reason: `the preview answered with HTTP ${response.status}` };
}
</code></pre>
<p>A network error or a gateway status blocks every selected test, and Playwright never starts. Pointing the demo at a port with nothing on it gives you this:</p>
<pre><code class="language-text">$ katalepsis run --cwd apps/demo-form --url http://127.0.0.1:4999
katalepsis: BLOCKED
  0 passed, 0 failed, 3 blocked, 0 not tested
  preview-unavailable: http://127.0.0.1:4999/ did not respond (connect ECONNREFUSED 127.0.0.1:4999). Playwright was not run.
</code></pre>
<h3 id="heading-playwrights-verdict-is-final">Playwright's Verdict is Final</h3>
<p><code>run</code> starts the project's own Playwright with <code>--reporter=json</code> and reads the result file, rather than reimplementing anything. Playwright already marks a test that passed on retry as <code>flaky</code>, so katalepsis keeps that flag and lists every attempt.</p>
<p>What it does add is classification. A failure whose message names the preview's own origin as unreachable becomes blocked, but a dead third-party API stays failed, because that's a real problem with your app. A browser that couldn't launch is blocked too, which is exactly what I got the first time I ran the demo for this article on a machine with the wrong browser build installed.</p>
<h3 id="heading-the-model-doesnt-get-to-call-something-a-pass">The Model Doesn't Get to Call Something a Pass</h3>
<p>The model in <code>verify</code> can click and type and read the page, but it doesn't get to call something a pass. A check only passes if the model points to a browser assertion that katalepsis ran, that passed, and that shows something that wasn't on the page before the model acted. Otherwise it comes back blocked.</p>
<p>Here's how that works. The model only gets a small set of tools: <code>navigate</code>, <code>snapshot</code>, <code>click</code>, <code>fill</code>, <code>press</code>, <code>assert</code>, and <code>finish</code>. <code>assert</code> doesn't return the model's opinion. katalepsis runs the check in the browser itself, takes a screenshot, and records the result with an ID like <code>a3</code>. When the model calls <code>finish</code>, it has to cite those IDs:</p>
<pre><code class="language-ts">finish: tool({
  description: "Report the verdict once, citing assertion IDs such as a1.",
  inputSchema: schema(
    Schema.Struct({
      verdict: Schema.Literals(["passed", "failed", "blocked"]),
      summary: Schema.String,
      assertionIds: Schema.Array(Schema.String),
    }),
  ),
  execute: (verdict) =&gt; {
    onFinish(verdict);
    return "Recorded.";
  },
}),
</code></pre>
<p>Then a plain function, <code>decideOutcome</code>, compares the claim with the evidence. A trimmed version of the pass rule:</p>
<pre><code class="language-ts">if (!cited.every((assertion) =&gt; assertion.passed)) {
  return "The agent reported a pass, but a cited assertion failed.";
}
const shown = cited.filter((assertion) =&gt; assertion.expectation === "visible");
if (shown.length === 0) {
  return "The agent reported a pass citing only hidden or URL assertions.";
}
if (!observeOnly &amp;&amp; shown.every((assertion) =&gt; assertion.trueAtStart === true)) {
  return "The agent reported a pass, but everything it cited was already on the page before it acted.";
}
</code></pre>
<p>Any of those messages turns the check into blocked with the code <code>no-evidence</code>. Citing an assertion ID that never ran is blocked too. The function also blocks a pass if an uncited assertion failed after the last cited one, because the latest evidence disagrees with the verdict.</p>
<p>That <code>trueAtStart</code> condition exists because one of the models I tested tried to prove a form worked by citing the label of the email field, which had been there all along. T</p>
<p>o catch it, each check opens two copies of the start page in separate browser contexts. The model works in one, and the other stays untouched. When the model asserts that something is visible, katalepsis looks for the same element on the untouched copy, and if it's there too, the assertion gets <code>trueAtStart: true</code> and can't carry a pass on its own.</p>
<h3 id="heading-one-action-at-a-time">One Action at a Time</h3>
<p>The first live runs also caught parallel tool calls stepping on each other, and a name ending up typed into the email field. Models like to send several tool calls at once, and two <code>fill</code> calls racing each other type into whichever field has focus. The fix is a promise queue that every browser action goes through:</p>
<pre><code class="language-ts">private exclusive&lt;A&gt;(action: () =&gt; Promise&lt;A&gt;): Promise&lt;A&gt; {
  const next = this.queue.then(action, action);
  this.queue = next.catch(() =&gt; undefined);
  return next;
}
</code></pre>
<p>Each action waits for the previous one to settle, whether it succeeded or failed, and a failure doesn't poison the queue for the next action.</p>
<h3 id="heading-budgets-and-boundaries">Budgets and Boundaries</h3>
<p>Each agent check runs in its own browser context with tracing on, so the report always has a trace to replay. Navigation is limited to the preview's origin plus anything you allow with <code>--allow-origin</code>. The model has a step limit (<code>--max-steps</code>, 15 by default), a token limit (<code>--max-tokens</code>, 200,000), and a time limit (<code>--check-timeout</code>, 120 seconds), and running out of any of them is reported as blocked with the reason, not as a failure. Query strings are redacted from URLs in the report.</p>
<h3 id="heading-how-it-was-built">How it Was Built</h3>
<p>Before writing code, I wrote a build plan split into milestones. M0 was a review of how two of my earlier projects handled credentials and providers, plus the first architecture decision record and the monorepo tooling. M1 was the Playwright runner and the report, M2 was agent checks with your own key, and M3 was the MCP server. Each milestone ended with a fresh agent with no history reviewing the work against the plan, the same independent-reviewer rule from earlier in this article.</p>
<p>Those reviews shaped the tool more than the plan did. The first one came back with 15 findings, including the rule that only an unreachable preview counts as blocked while other hosts stay failed. The M2 review found that a model could get a pass by citing an assertion that proved nothing, which is where the stricter pass rule and the untouched copy of the page came from. The M3 review found that a client quitting mid-run left Playwright and its browsers running, and that a crafted symlink could let the report tool read files outside the project. All of those are fixed and covered by tests now.</p>
<h2 id="heading-what-happened-when-i-used-it">What Happened When I Used It</h2>
<p>Before telling anyone about it, I ran it against two of my own projects. Conclave's suite came back with 95 passed. A larger app came back with 137 passed and one failure, an assertion on a zoom level that was slightly off.</p>
<p>That was a test I already had and hadn't noticed was failing, so katalepsis didn't find the bug so much as make it impossible to miss. Both projects also hardcoded their <code>baseURL</code>, which meant their tests never touched the URL I passed in. katalepsis now warns about that, because a green run against the wrong server is worse than no run.</p>
<p>After I posted it on LinkedIn, someone in the comments pointed out that the commit you have checked out isn't necessarily the commit the preview was built from. They were right, so the report now records both and marks them confirmed, mismatched, or unknown, and a mismatch blocks a run that would otherwise pass, since a green run against a stale preview tells you nothing about your diff.</p>
<p>The preview reports its commit with an <code>x-commit-sha</code> response header or a <code>&lt;meta name="commit-sha"&gt;</code> tag, which the same probe that checks availability reads. If your host can't do either, you can pass <code>--preview-commit</code> yourself.</p>
<p>I'm dogfooding it in the same instructions this article describes. The browser-review skill now tells my agents to run katalepsis first, and to fall back to plain browser automation for what it can't check yet: field values, persistence, console and network, and layout across viewports.</p>
<p>The first Codex session to pick that up went looking for a "katalepsis skill" because of how I'd worded the line in <code>AGENTS.md</code>, didn't find one, and fell back to its old browser review. Wrong for a silly reason, but the fallback did exactly what it was supposed to, and the fix was saying plainly that katalepsis is a CLI and browser-review is the skill.</p>
<p>A few days later I used it on a real work branch, a change that made GeoJSON the main download button and moved CSV and KML into a dropdown. The agent stopped before running anything, because <code>verify</code> sends page content to the model provider and my rules say it needs my OK before doing that for an app. That's the behavior I want</p>
<p>With seeded synthetic data and an explicit OK, the check passed: one visible primary button, and the other formats showing up once the dropdown opened, with the screenshots and trace in the report. The skill still keeps pages with real data on the fallback path.</p>
<h2 id="heading-where-i-landed">Where I Landed</h2>
<p>Not every task needs any of this. I don't need Playwright to confirm a Markdown typo got fixed, and a backend refactor that can't change what renders doesn't need Chromium. I do want it for components, forms, navigation, dialogs, client state, maps, filtering, responsive layout, persistence, and any user-visible bug fix.</p>
<p>My rule of thumb is that if you're making a claim about how the UI behaves at runtime, the runtime UI should be part of the evidence.</p>
<p>None of this replaces good tests, code review, or me looking at changes that matter. It just adds the feedback loop that was missing. The agent already has the repository and the shell, and it knows what it changed. With a browser it can start answering whether the thing it built actually works, and with a report it can show me instead of telling me. If it can write the button, it can click it and show me what happened before it says it's done.</p>
<p>katalepsis is MIT licensed and on <a href="https://github.com/glamboyosa/katalepsis">GitHub</a>. If an agent check ever gives you a result you don't believe, I'd like to hear about it.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build Disaster Simulations on a Real Map: Animated Canvas Layers and Collapsing 3D Buildings with Mapbox GL JS and Three.js ]]>
                </title>
                <description>
                    <![CDATA[ At some point, a map project needs more than markers and polygons. You want something to happen on the map: water moving up a street, smoke drifting with the wind, or a shockwave spreading out from a  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/disaster-simulation-real-map-mapbox-three-js/</link>
                <guid isPermaLink="false">6ad05935fb11435ce8281161</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ canvas ]]>
                    </category>
                
                    <category>
                        <![CDATA[ mapbox ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Alex Oliinyk ]]>
                </dc:creator>
                <pubDate>Thu, 15 Oct 2026 04:40:21 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/db541c6a-aba6-4a25-b0f8-2a4657c485d3.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>At some point, a map project needs more than markers and polygons. You want something to happen on the map: water moving up a street, smoke drifting with the wind, or a shockwave spreading out from a point.</p>
<p>The first time I tried this, I did what seemed obvious to me. I put a <code>&lt;canvas&gt;</code> on top of the map and drew my animation on it.</p>
<p>But it looked wrong in a way I couldn't fix with more polish. The effect had edges. It floated above the ground. And as soon as I tilted or rotated the map, it stopped lining up with anything underneath.</p>
<p>I hit this while building <a href="https://hazardsim.com/">HazardSim</a>, a browser simulator that runs natural disasters on a real map. The tsunami scenario went through about a dozen rewrites before it stopped looking like a cut-out pasted over the city.</p>
<p>Much of the testing, and a good share of the bug reports, came from my 12-year-old son Tim, who turned out to be a more patient tester than I am. Most of those rewrites taught me the same thing from a different direction: <strong>draw your simulation in map coordinates, not screen coordinates.</strong></p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/a7c17a37-4c30-48a9-be44-89da78f6c14f.jpg" alt="Left: a video clip of a breaking wave drawn on a canvas overlaid on the map. It is a rectangle floating over Odesa with visible soft edges. Right: the same second of the simulation with the water painted into a canvas that the map treats as a raster source. The water follows the coastline and the tilt of the camera." style="display: block;" width="2238" height="878" loading="lazy">

<p>That rule carried me through the tsunami. Then I started on the earthquake and ran into the opposite problem. Mapbox GL JS will draw a city in 3D for you: turn on a <code>fill-extrusion</code> layer and every footprint in the vector tiles rises to its real height.</p>
<p>It looks good until you try to make one of those buildings fall down, and you find out that the map's 3D is a rendering trick, not a scene. There are no objects to grab, rotate or break. Things that lie on the ground and things that have height turned out to need two different techniques, and this guide covers both.</p>
<p><strong>Part 1</strong> builds the ground layer. You'll set up a grid aligned to the map's own tiles, load real elevation data into it, run a flood fill that respects hills and valleys, hand the canvas to the map as a raster source, write pixels into it every frame, layer video textures on top with canvas compositing modes, and move the camera into the scene.</p>
<p><strong>Part 2</strong> adds height. You'll pull building footprints and heights out of the map's tiles, make the extrusions look like buildings, decide which ones fall from the magnitude and distance, animate the collapse without rebuilding any layers, set up a <code>three.js</code> custom layer inside the map's own WebGL context, turn a footprint into a box that tips over, throw debris and dust, and shake the camera.</p>
<p>At the end we'll go through the mistakes from both halves, several of which produce no error message and cost me a day each.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>You should be comfortable with JavaScript, <code>requestAnimationFrame</code>, and the basics of the 2D canvas API: <code>getContext("2d")</code>, <code>drawImage</code>, and <code>ImageData</code>.</p>
<p>You don't need any background in web maps. Everything map-specific is explained where it comes up.</p>
<p>Part 2 also assumes you've used <code>three.js</code> at least once: meshes, materials, a scene and a camera. If you haven't, the three.js fundamentals are enough to follow along, and the parts that interact with the map are explained in full.</p>
<p>The examples use <a href="https://docs.mapbox.com/mapbox-gl-js/">Mapbox GL JS</a>, which is what runs on HazardSim. You'll need a free Mapbox access token for the base map and the vector tiles. Every API used here also exists in <a href="https://maplibre.org/">MapLibre GL JS</a>, the open-source fork, under the same names. The one place the two differ is called out in Part 2.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-part-1-drawing-on-the-ground">Part 1: Drawing on the Ground</a></p>
</li>
<li><p><a href="#heading-the-core-idea-map-space-not-screen-space">The Core Idea: Map Space, Not Screen Space</a></p>
</li>
<li><p><a href="#heading-step-1-choose-a-grid-aligned-to-map-tiles">Step 1: Choose a Grid Aligned to Map Tiles</a></p>
</li>
<li><p><a href="#heading-step-2-load-real-elevation-into-the-grid">Step 2: Load Real Elevation Into the Grid</a></p>
</li>
<li><p><a href="#heading-step-3-attach-a-canvas-as-a-map-source">Step 3: Attach a Canvas as a Map Source</a></p>
</li>
<li><p><a href="#heading-step-4-simulate-a-flood-that-respects-the-terrain">Step 4: Simulate a Flood That Respects the Terrain</a></p>
</li>
<li><p><a href="#heading-step-5-animate-by-writing-pixels">Step 5: Animate by Writing Pixels</a></p>
</li>
<li><p><a href="#heading-step-6-layer-video-textures-with-canvas-compositing">Step 6: Layer Video Textures With Canvas Compositing</a></p>
</li>
<li><p><a href="#heading-step-7-move-the-camera-into-the-scene">Step 7: Move the Camera Into the Scene</a></p>
</li>
<li><p><a href="#heading-where-the-ground-layer-stops">Where the Ground Layer Stops</a></p>
</li>
<li><p><a href="#heading-part-2-things-with-height">Part 2: Things with Height</a></p>
</li>
<li><p><a href="#heading-two-kinds-of-3d-and-why-you-need-both">Two Kinds of 3D, and Why You Need Both</a></p>
</li>
<li><p><a href="#heading-step-8-get-buildings-out-of-the-maps-own-tiles">Step 8: Get Buildings Out of the Map's Own Tiles</a></p>
</li>
<li><p><a href="#heading-step-9-make-extrusions-look-like-buildings">Step 9: Make Extrusions Look Like Buildings</a></p>
</li>
<li><p><a href="#heading-step-10-decide-what-falls">Step 10: Decide What Falls</a></p>
</li>
<li><p><a href="#heading-step-11-animate-collapse-without-rebuilding-layers">Step 11: Animate Collapse Without Rebuilding Layers</a></p>
</li>
<li><p><a href="#heading-step-12-a-threejs-scene-inside-the-map">Step 12: A three.js Scene Inside the Map</a></p>
</li>
<li><p><a href="#heading-step-13-from-footprint-to-a-box-that-tips-over">Step 13: From Footprint to a Box That Tips Over</a></p>
</li>
<li><p><a href="#heading-step-14-debris-and-dust">Step 14: Debris and Dust</a></p>
</li>
<li><p><a href="#heading-step-15-the-camera-has-to-shake">Step 15: The Camera Has to Shake</a></p>
</li>
<li><p><a href="#heading-keeping-it-fast">Keeping It Fast</a></p>
</li>
<li><p><a href="#heading-what-went-wrong-and-why">What Went Wrong, and Why</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-part-1-drawing-on-the-ground">Part 1: Drawing on the Ground</h2>
<p>The first half of this guide is about anything that belongs to the surface of the map: water, fire spread, a smoke stain, or a shockwave. The technique is one idea applied carefully, and the next seven steps build it up from a grid to a camera move.</p>
<h2 id="heading-the-core-idea-map-space-not-screen-space">The Core Idea: Map Space, Not Screen Space</h2>
<p>A web map is a camera looking at a surface. When the user drags, zooms, tilts or rotates, the camera moves and the surface stays where it is. Roads, buildings, and your flood all belong to the surface, so the camera has to transform them together.</p>
<p>A canvas placed over the map's DOM element is attached to the camera, not to the surface. Think of it as a sheet of glass in front of the lens. Whatever you draw on it stays where you drew it while the world moves underneath.</p>
<p>At a top-down zoom with no rotation, you can fake alignment by reprojecting your points every frame, and it almost works. Add pitch and it falls apart: a flat sprite has no perspective, no foreshortening, and nothing in front of or behind it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/fbcc5755-b979-4e21-86f4-79f16e27bbc9.png" alt="Two diagrams side by side. Left, titled &quot;Canvas on top of the map&quot;: a tilted map surface with a flat blue rectangle standing upright over it, labelled &quot;flat sprite&quot;, with the note &quot;no perspective, visible edges, doesn't rotate with the map&quot;. Right, titled &quot;Canvas as a map source&quot;: the same tilted surface with the blue area lying flat on it as a trapezoid, labelled &quot;same pixels, foreshortened&quot;, with the note &quot;perspective for free, no edges, rotates, tilts, follows terrain&quot;." style="display: block;" width="2960" height="1240" loading="lazy">

<p>The fix is to give your canvas to the map as a data source. Mapbox GL JS has a <code>canvas</code> source type. You pass it a canvas element and four geographic corners, and from then on the map drapes that canvas over the rectangle the same way it drapes satellite imagery. Rotate the map and the canvas rotates. Tilt it and the canvas foreshortens. Turn on 3D terrain and the canvas follows the hills.</p>
<p>Once the drawing surface lives in map space, several hard problems disappear. The rest of this handbook is about what you can do with that.</p>
<h2 id="heading-step-1-choose-a-grid-aligned-to-map-tiles">Step 1: Choose a Grid Aligned to Map Tiles</h2>
<p>Your simulation needs a grid: a 2D array of cells, each holding elevation, water depth, or whatever your model tracks. The decision that makes everything downstream simpler is to align that grid to the map's own tile pyramid.</p>
<p>Web maps use the Web Mercator projection, cut into 256×256-pixel tiles at zoom levels 0 to 22. At zoom <code>z</code> the world is <code>2^z</code> tiles wide. If one grid cell is exactly one tile pixel at some zoom, converting between grid indices and longitude/latitude takes four short functions, and every dataset that ships as tiles (elevation, population, imagery) drops into your grid without resampling.</p>
<p>Here are the four conversions. <code>lon2x</code> and <code>lat2y</code> return fractional tile coordinates. Multiply by 256 to get pixels.</p>
<pre><code class="language-javascript">function lon2x(lon, z) {
  return (lon + 180) / 360 * Math.pow(2, z);
}

function lat2y(lat, z) {
  const rad = lat * Math.PI / 180;
  return (1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2 * Math.pow(2, z);
}

function x2lon(x, z) {
  return x / Math.pow(2, z) * 360 - 180;
}

function y2lat(y, z) {
  const n = Math.PI - 2 * Math.PI * y / Math.pow(2, z);
  return 180 / Math.PI * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
}
</code></pre>
<p>Next, pick the zoom. You want the area of interest to fit in a grid that's fine enough to look smooth but small enough to iterate over sixty times a second. In HazardSim, I start at zoom 15 and step down until the bounding box fits in roughly 780 pixels across and under about 620,000 cells:</p>
<pre><code class="language-javascript">function chooseZoom(bbox) {
  for (let z = 15; z &gt;= 8; z--) {
    const pw = (lon2x(bbox.e, z) - lon2x(bbox.w, z)) * 256;
    const ph = (lat2y(bbox.s, z) - lat2y(bbox.n, z)) * 256;
    if (pw &lt;= 780 &amp;&amp; pw * ph &lt;= 620000) return z;
  }
  return 8;
}
</code></pre>
<p>With the zoom chosen, snap the bounding box outward to whole tiles. That rectangle is what your canvas will cover, and those are the tiles you'll download:</p>
<pre><code class="language-javascript">function gridFor(bbox) {
  const z = chooseZoom(bbox);
  const x0 = Math.floor(lon2x(bbox.w, z)), x1 = Math.floor(lon2x(bbox.e, z));
  const y0 = Math.floor(lat2y(bbox.n, z)), y1 = Math.floor(lat2y(bbox.s, z));
  const nx = x1 - x0 + 1, ny = y1 - y0 + 1;
  const latMid = (bbox.n + bbox.s) / 2;

  return {
    z, x0, y0, nx, ny,
    W: nx * 256,
    H: ny * 256,
    // metres per cell at this latitude and zoom
    cellM: 156543.03392 * Math.cos(latMid * Math.PI / 180) / Math.pow(2, z),
    // exact geographic corners of the snapped rectangle
    corners: {
      w: x2lon(x0, z), e: x2lon(x1 + 1, z),
      n: y2lat(y0, z), s: y2lat(y1 + 1, z),
    },
  };
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/2b47daac-24cc-42e9-b6f0-fb110bb13aa8.png" alt="Diagram of a 4 by 3 arrangement of map tiles with orange tile borders. A dashed blue rectangle inside marks the city bounding box. One tile is subdivided into small cells to show that one grid cell is one tile pixel. A side panel lists why aligning to tiles helps and shows the conversion formulas." style="display: block;" width="2800" height="1400" loading="lazy">

<p>Keep <code>cellM</code> around. You'll need it to turn "the wave has travelled 400 metres" into "the wave has travelled 3.8 cells". For Odesa, the city in most of the screenshots here, the grid ends up at zoom 10 with 105-metre cells.</p>
<h2 id="heading-step-2-load-real-elevation-into-the-grid">Step 2: Load Real Elevation Into the Grid</h2>
<p>A flood that ignores hills is a blue blob. What makes a simulation on a real map feel real is real terrain, and terrain is free.</p>
<p>The AWS Open Data program hosts the Mapzen <strong>Terrarium</strong> elevation tiles. They're ordinary PNGs with height encoded in the pixel colour:</p>
<pre><code class="language-javascript">height_m = R * 256 + G + B / 256 - 32768
</code></pre>
<p>Because the grid is tile-aligned, loading elevation means fetching the tiles, drawing them onto one big canvas in their natural positions, reading the pixels back, and decoding. Nothing is resampled. The grid cell and the elevation sample are the same pixel.</p>
<pre><code class="language-javascript">function terrariumUrl(z, x, y) {
  return `https://s3.amazonaws.com/elevation-tiles-prod/terrarium/${z}/${x}/${y}.png`;
}

function loadImage(url) {
  return new Promise((resolve, reject) =&gt; {
    const img = new Image();
    img.crossOrigin = "anonymous";
    img.onload = () =&gt; resolve(img);
    img.onerror = reject;
    img.src = url;
  });
}

async function loadElevation(grid) {
  const cv = document.createElement("canvas");
  cv.width = grid.W;
  cv.height = grid.H;
  const cx = cv.getContext("2d", { willReadFrequently: true });

  const jobs = [];
  for (let iy = 0; iy &lt; grid.ny; iy++) {
    for (let ix = 0; ix &lt; grid.nx; ix++) {
      jobs.push(
        loadImage(terrariumUrl(grid.z, grid.x0 + ix, grid.y0 + iy))
          .then(img =&gt; cx.drawImage(img, ix * 256, iy * 256))
      );
    }
  }
  await Promise.all(jobs);

  const d = cx.getImageData(0, 0, grid.W, grid.H).data;
  const elev = new Float32Array(grid.W * grid.H);
  for (let i = 0; i &lt; elev.length; i++) {
    const o = i * 4;
    elev[i] = d[o] * 256 + d[o + 1] + d[o + 2] / 256 - 32768;
  }
  return elev;
}
</code></pre>
<p><code>crossOrigin = "anonymous"</code> is required. Without it the canvas becomes "tainted" and <code>getImageData</code> throws. The Terrarium bucket sends the right CORS headers, so this works as written.</p>
<p>Since you already have a Mapbox token, you can use Mapbox's own <strong>Terrain-RGB</strong> tiles instead. The URL is <code>https://api.mapbox.com/v4/mapbox.terrain-rgb/{z}/{x}/{y}.pngraw?access_token=…</code> and the decode formula is different:</p>
<pre><code class="language-javascript">// Mapbox Terrain-RGB
elev[i] = -10000 + (d[o] * 65536 + d[o + 1] * 256 + d[o + 2]) * 0.1;
</code></pre>
<p>HazardSim supports both and switches with a config flag. Terrain-RGB is cleaner data with fewer spikes. Terrarium is free of per-tile billing. For a tutorial, I'd start with Terrarium.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/e8f721b6-ff2d-44b6-9bb0-3c0830ada2ba.png" alt="Decoded elevation for the coast around Odesa rendered as a greyscale heightmap, with the sea in dark blue and higher ground lighter. Orange lines show the boundaries of the 4 by 4 Terrarium tiles that were stitched together." style="display: block;" width="1024" height="1090" loading="lazy">

<p>Two practical notes. Terrarium data has occasional single-pixel spikes, and a 3×3 median pass over cells that differ from all their neighbours by more than a few metres cleans them up. And cells at or below zero are sea, except where they aren't, like in the Netherlands, New Orleans, or Death Valley. I treat <code>elev &lt;= 0</code> as sea only when the cell connects to the map edge through other sea cells. That handles the common cases.</p>
<h2 id="heading-step-3-attach-a-canvas-as-a-map-source">Step 3: Attach a Canvas as a Map Source</h2>
<p>Now the central move. Create a canvas the size of your grid and register it with the map as a <code>canvas</code> source whose four corners are the snapped rectangle from Step 1.</p>
<pre><code class="language-html">&lt;div id="map"&gt;&lt;/div&gt;
&lt;canvas id="floodcanvas" width="10" height="10" style="display:none"&gt;&lt;/canvas&gt;
</code></pre>
<pre><code class="language-javascript">mapboxgl.accessToken = "YOUR_MAPBOX_TOKEN";

const map = new mapboxgl.Map({
  container: "map",
  style: "mapbox://styles/mapbox/satellite-streets-v12",
  center: [30.73, 46.48],
  zoom: 11,
});

const fc = document.getElementById("floodcanvas");
const fctx = fc.getContext("2d");
let fimg = null;

function attachCanvas(grid) {
  fc.width = grid.W;
  fc.height = grid.H;
  fimg = fctx.createImageData(grid.W, grid.H);

  const c = grid.corners;
  const coords = [[c.w, c.n], [c.e, c.n], [c.e, c.s], [c.w, c.s]];

  if (map.getSource("flood")) {
    map.getSource("flood").setCoordinates(coords);
    return;
  }
  map.addSource("flood", {
    type: "canvas",
    canvas: "floodcanvas",
    coordinates: coords,
    animate: true,
  });
  map.addLayer({
    id: "flood",
    type: "raster",
    source: "flood",
    paint: {
      "raster-opacity": 0.94,
      "raster-resampling": "linear",
      "raster-fade-duration": 0,
    },
  });
}
</code></pre>
<p>Three options matter here:</p>
<ul>
<li><p><code>animate: true</code> tells Mapbox GL to re-upload the canvas as a texture every frame. Without it, the animation freezes on the first frame.</p>
</li>
<li><p><code>"raster-resampling": "linear"</code> blends between cells when the user zooms in past your grid resolution. With 105-metre cells at a city zoom, it's the difference between water and a pixel-art game.</p>
</li>
<li><p><code>"raster-fade-duration": 0</code> turns off the cross-fade Mapbox GL applies to raster tiles. You're redrawing every frame, and a fade only smears it.</p>
</li>
</ul>
<p>The canvas is <code>display:none</code> because the map reads it directly. It never needs to be visible in the DOM.</p>
<p>From here on, anything you write into <code>fimg</code> and push with <code>fctx.putImageData(fimg, 0, 0)</code> shows up on the map in the right place, at any pitch and bearing, draped over terrain if terrain is on. The rendering problem has turned into a pixel-array problem.</p>
<h2 id="heading-step-4-simulate-a-flood-that-respects-the-terrain">Step 4: Simulate a Flood That Respects the Terrain</h2>
<p>A tsunami doesn't flood everything below the wave height. Water has to get there. It enters from the sea, flows over low ground, and stops where the ground rises above the water level, even if there's lower ground on the far side of a ridge. That's a connectivity problem, and breadth-first search is the tool for it.</p>
<p>First, a distance field: how far is each cell from the coast? Seed the queue with every sea cell adjacent to land, then expand into the sea. You'll use this to animate the wave approaching, and the land-side equivalent to animate it spreading inland.</p>
<pre><code class="language-javascript">function seaDistance(grid, sea) {
  const { W, H, cellM } = grid;
  const N = W * H;
  const dist = new Float32Array(N).fill(-1);
  const q = new Int32Array(N);
  let head = 0, tail = 0;

  // seed: sea cells that touch land
  for (let i = 0; i &lt; N; i++) {
    if (!sea[i]) continue;
    const x = i % W, y = (i / W) | 0;
    const touchesLand =
      (x &gt; 0 &amp;&amp; !sea[i - 1]) || (x &lt; W - 1 &amp;&amp; !sea[i + 1]) ||
      (y &gt; 0 &amp;&amp; !sea[i - W]) || (y &lt; H - 1 &amp;&amp; !sea[i + W]);
    if (touchesLand) { dist[i] = 0; q[tail++] = i; }
  }

  // expand
  while (head &lt; tail) {
    const c = q[head++];
    const cx = c % W, cy = (c / W) | 0;
    for (let dy = -1; dy &lt;= 1; dy++) {
      for (let dx = -1; dx &lt;= 1; dx++) {
        if (!dx &amp;&amp; !dy) continue;
        const nx = cx + dx, ny = cy + dy;
        if (nx &lt; 0 || ny &lt; 0 || nx &gt;= W || ny &gt;= H) continue;
        const n = ny * W + nx;
        if (!sea[n] || dist[n] &gt;= 0) continue;
        dist[n] = dist[c] + (dx &amp;&amp; dy ? cellM * Math.SQRT2 : cellM);
        q[tail++] = n;
      }
    }
  }
  return dist;
}
</code></pre>
<p>The flood is the same search in the other direction, with one extra rule: a cell is reachable only if the water surface is above its ground. <code>waveH</code> is the wave height at the shore in metres. The water loses height as it travels inland, and a linear decay is enough to look right:</p>
<pre><code class="language-javascript">function floodFill(grid, elev, sea, waveH) {
  const { W, H, cellM } = grid;
  const N = W * H;
  const depth = new Float32Array(N);       // metres of water above ground
  const reach = new Float32Array(N).fill(-1); // distance from shore, metres
  const q = new Int32Array(N);
  let head = 0, tail = 0;

  for (let i = 0; i &lt; N; i++) {
    if (!sea[i]) continue;
    const x = i % W, y = (i / W) | 0;
    const nb = [i - 1, i + 1, i - W, i + W];
    for (const n of nb) {
      if (n &lt; 0 || n &gt;= N || sea[n] || reach[n] &gt;= 0) continue;
      if ((n === i - 1 &amp;&amp; x === 0) || (n === i + 1 &amp;&amp; x === W - 1)) continue;
      reach[n] = 0;
      q[tail++] = n;
    }
  }

  const decayPerM = waveH / 12000; // loses its height over ~12 km

  while (head &lt; tail) {
    const c = q[head++];
    const level = waveH - reach[c] * decayPerM;
    const d = level - elev[c];
    if (d &lt;= 0) continue;               // ground is above the water here: stop
    depth[c] = d;

    const cx = c % W, cy = (c / W) | 0;
    for (let dy = -1; dy &lt;= 1; dy++) {
      for (let dx = -1; dx &lt;= 1; dx++) {
        if (!dx &amp;&amp; !dy) continue;
        const nx = cx + dx, ny = cy + dy;
        if (nx &lt; 0 || ny &lt; 0 || nx &gt;= W || ny &gt;= H) continue;
        const n = ny * W + nx;
        if (sea[n] || reach[n] &gt;= 0) continue;
        reach[n] = reach[c] + (dx &amp;&amp; dy ? cellM * Math.SQRT2 : cellM);
        q[tail++] = n;
      }
    }
  }
  return { depth, reach };
}
</code></pre>
<p>Run this once per scenario, not per frame. On a 700×500 grid it takes a few milliseconds. The outputs, <code>depth</code> for every cell and <code>reach</code> for how far inland it is, are all the animation needs.</p>
<p>Because the fill follows real elevation, it goes up river valleys and stops at embankments. Multiply the flooded cell count by <code>cellM²</code> and you get a flooded area in square kilometres you can stand behind.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/171566ef-f912-4a90-894f-ae4adda8e252.jpg" alt="Top-down view of Odesa after the simulated tsunami. Dark brown water covers the low coastal districts and the port, following the shape of the coastline and stopping at higher ground inland. The open sea stays its normal dark blue." style="display: block;" width="1095" height="790" loading="lazy">

<h2 id="heading-step-5-animate-by-writing-pixels">Step 5: Animate by Writing Pixels</h2>
<p>The frame loop does one thing. For each flooded land cell, it decides whether the water has arrived yet, and if so, what colour it is.</p>
<p>"Arrived" is a comparison of the cell's <code>reach</code> against a front position <code>F</code> that grows with time. Add some per-cell noise to <code>reach</code> so the front isn't a perfect contour line, and the water starts to look like water:</p>
<pre><code class="language-javascript">let t0 = null;
const T_LANDFALL = 3.9;   // seconds until the wave reaches the shore
const T_FULL = 10.9;      // seconds until it reaches its maximum extent

function ease(k) {
  return k &lt;= 0 ? 0 : k &gt;= 1 ? 1 : 1 - Math.pow(1 - k, 2.2);
}

function frame(now) {
  if (t0 === null) t0 = now;
  const t = (now - t0) / 1000;
  const d = fimg.data;
  const { W, H } = grid;

  // how far inland the front has got, in metres
  const F = t &lt; T_LANDFALL
    ? -1e9
    : maxReach * ease((t - T_LANDFALL) / (T_FULL - T_LANDFALL));

  for (let i = 0; i &lt; W * H; i++) {
    const o = i * 4;
    if (sea[i] || depth[i] &lt;= 0) { d[o + 3] = 0; continue; }

    const arrival = reach[i] + noise[i] * 180;   // ±90 m of jitter
    if (arrival &gt; F) { d[o + 3] = 0; continue; }

    const age = (F - arrival) / 150;             // how long the cell has been under
    const dp = depth[i];

    // base colour: shallow is lighter, deep is darker
    let r = 40 + Math.max(0, 60 - dp * 10);
    let g = 70 + Math.max(0, 50 - dp * 8);
    let b = 95 + Math.max(0, 40 - dp * 6);
    let a = dp &lt; 0.5 ? 215 + dp * 60 : 245;

    // the leading edge is foam: push toward white for the first moments
    if (age &lt; 1.4) {
      const k = Math.pow(1 - age / 1.4, 2) * 0.8;
      r += (240 - r) * k; g += (246 - g) * k; b += (246 - b) * k;
    }

    d[o] = r; d[o + 1] = g; d[o + 2] = b; d[o + 3] = a;
  }

  fctx.putImageData(fimg, 0, 0);
  if (t &lt; T_FULL + 3) requestAnimationFrame(frame);
}

requestAnimationFrame(frame);
</code></pre>
<p><code>noise</code> is a <code>Float32Array</code> of random values in <code>[-0.5, 0.5]</code> generated once per run. <code>maxReach</code> is the largest <code>reach</code> value among flooded cells.</p>
<p>There are two performance points: A 700×500 grid is 350,000 cells, and this loop runs at 60 fps on my laptop and around 30 fps on a mid-range phone. If you need more, iterate only over the list of flooded land cells (collect the indices once after <code>floodFill</code>) instead of the whole grid. In a coastal city, that's usually a quarter of the cells. And keep <code>fimg</code> between frames. Calling <code>createImageData</code> every frame is the first thing a profiler will point at.</p>
<p>If you stop here, you have a working, terrain-aware simulation. The rest is about making it look like footage instead of a diagram.</p>
<h2 id="heading-step-6-layer-video-textures-with-canvas-compositing">Step 6: Layer Video Textures With Canvas Compositing</h2>
<p>Flat colour reads as a diagram. Real water has texture that moves. The cheapest way to get that is to drape a looping video of real water over the flooded area, and the restriction "over the flooded area only" comes free from two canvas compositing modes:</p>
<ul>
<li><p><code>source-atop</code> draws the new image only where the destination already has pixels. Draw a video onto the flood canvas with <code>source-atop</code> and it appears on water only. Dry land stays untouched, because dry land is transparent.</p>
</li>
<li><p><code>destination-in</code> keeps the destination only where the new image has pixels. Draw a black-and-transparent mask onto a buffer with <code>destination-in</code>, and the buffer is cropped to the mask's shape.</p>
</li>
</ul>
<p>You need a hidden <code>&lt;video&gt;</code> (muted, looping, and <code>playsInline</code>. You need all three, or mobile Safari refuses to autoplay) and one scratch canvas the size of the grid:</p>
<pre><code class="language-javascript">const vid = document.createElement("video");
vid.muted = true; vid.loop = true; vid.playsInline = true;
vid.setAttribute("muted", ""); vid.setAttribute("playsinline", "");
vid.src = "/fx/water.webm";
vid.style.cssText = "position:absolute;width:1px;height:1px;opacity:0;pointer-events:none";
document.body.appendChild(vid);
vid.load();

const buf = document.createElement("canvas");
buf.width = grid.W; buf.height = grid.H;
const bctx = buf.getContext("2d");

function drawWaterTexture(mud) {
  if (vid.readyState &lt; 2) return;         // not enough data yet: skip, don't block
  if (vid.paused) vid.play().catch(() =&gt; {});

  // 1. video into the scratch buffer, stretched to the grid
  bctx.globalCompositeOperation = "source-over";
  bctx.clearRect(0, 0, grid.W, grid.H);
  bctx.drawImage(vid, 0, 0, grid.W, grid.H);

  // 2. tint it, only where the video is (everywhere, at this point)
  bctx.globalCompositeOperation = "source-atop";
  bctx.globalAlpha = 0.5 + 0.38 * mud;
  bctx.fillStyle = `rgb(${28 + 108 * mud | 0}, ${112 - 10 * mud | 0}, ${178 - 126 * mud | 0})`;
  bctx.fillRect(0, 0, grid.W, grid.H);
  bctx.globalAlpha = 1;

  // 3. crop the buffer to land cells, so the open sea keeps its own colour
  bctx.globalCompositeOperation = "destination-in";
  bctx.drawImage(landMask, 0, 0);

  // 4. onto the flood canvas, only where there's already water
  fctx.save();
  fctx.globalCompositeOperation = "source-atop";
  fctx.globalAlpha = 0.8;
  fctx.drawImage(buf, 0, 0);
  fctx.restore();
}
</code></pre>
<p>Call this right after <code>fctx.putImageData(fimg, 0, 0)</code> in the frame loop. Step 4 is where it pays off. Because the flood canvas is transparent wherever there's no water, <code>source-atop</code> puts the texture exactly inside the flood outline, following every bay and valley the BFS found, with no per-pixel work on your side.</p>
<p><code>landMask</code> is a canvas you build once per run: white where <code>sea[i]</code> is false, transparent elsewhere. Without it the texture also covers the open sea, and the whole gulf turns the colour of the flood. I shipped that version for about an hour before I noticed.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/926abb5b-ba8a-4cf9-8eb9-2e343ad53313.jpg" alt="Pitched view from above the shore of Odesa, looking out to sea. A white foam front sweeps across the coast and into the city, following the coastline, with darker water behind it." style="display: block;" width="1095" height="790" loading="lazy">

<p>The <code>mud</code> parameter is a time ramp from 0 to 1. Tsunami water arrives as seawater and turns dark brown as it picks up sediment off the land. Interpolating the tint from sea blue to mud brown over a few seconds after landfall gives you that for free.</p>
<p>The first time I built this, I had baked a brown grade into the video file itself, and no amount of tinting could make the water blue at the start. Keep the source footage neutral and do colour in code.</p>
<p>The same <code>destination-in</code> trick gives you a depth-driven darkening (a mask whose alpha is proportional to <code>depth[i]</code>, filled with a dark colour) and a foam band along the moving front (a mask whose alpha is a Gaussian of <code>reach[i] - F</code>, filled with a second video of churning foam). Each is a few lines, and each one makes the water read a little more as a volume and a little less as a tint.</p>
<h2 id="heading-step-7-move-the-camera-into-the-scene">Step 7: Move the Camera Into the Scene</h2>
<p>A top-down map is an illustration. Tilt the camera and the same pixels become a place. The flood canvas is draped on the ground, so it foreshortens correctly. Your only job is to point the camera somewhere worth looking at.</p>
<p>For a tsunami, that means standing on the shore near the city, looking out to sea, and watching it come in. "Near the city" is the coastline cell closest to the map centre. "Out to sea" is the average direction to nearby sea cells from that point. Compute it locally rather than for the whole coastline, or a curved bay will point your camera at the wrong horizon. I found that out with Odesa, where the citywide average pointed the camera at empty fields next to the airport.</p>
<pre><code class="language-javascript">function shoreCamera(grid, sea, center) {
  const { W, H, z, x0, y0, cellM } = grid;

  // 1. nearest coastline cell to the map centre
  let best = -1, bestD = Infinity;
  for (let i = 0; i &lt; W * H; i++) {
    if (!sea[i]) continue;
    const x = i % W, y = (i / W) | 0;
    const coast = (x &gt; 0 &amp;&amp; !sea[i - 1]) || (x &lt; W - 1 &amp;&amp; !sea[i + 1]) ||
                  (y &gt; 0 &amp;&amp; !sea[i - W]) || (y &lt; H - 1 &amp;&amp; !sea[i + W]);
    if (!coast) continue;
    const lng = x2lon(x0 + (x + 0.5) / 256, z), lat = y2lat(y0 + (y + 0.5) / 256, z);
    const d = (lng - center.lng) ** 2 + (lat - center.lat) ** 2;
    if (d &lt; bestD) { bestD = d; best = i; }
  }
  const sx = best % W, sy = (best / W) | 0;

  // 2. local seaward direction: average offset to sea cells within ~2.5 km
  const r = Math.max(6, Math.round(2500 / cellM));
  let vx = 0, vy = 0;
  for (let dy = -r; dy &lt;= r; dy++) {
    for (let dx = -r; dx &lt;= r; dx++) {
      const x = sx + dx, y = sy + dy;
      if (x &lt; 0 || y &lt; 0 || x &gt;= W || y &gt;= H || !sea[y * W + x]) continue;
      const len = Math.hypot(dx, dy);
      if (len &lt; 1 || len &gt; r) continue;
      vx += dx / len; vy += dy / len;
    }
  }
  const len = Math.hypot(vx, vy) || 1;
  const east = vx / len, north = -vy / len;   // grid y grows southward

  const shoreLng = x2lon(x0 + (sx + 0.5) / 256, z);
  const shoreLat = y2lat(y0 + (sy + 0.5) / 256, z);
  const mLng = 111320 * Math.cos(shoreLat * Math.PI / 180), mLat = 111320;

  return {
    // stand 900 m inland of the shore...
    center: [shoreLng - east * 900 / mLng, shoreLat - north * 900 / mLat],
    // ...facing the sea
    bearing: Math.atan2(east, north) * 180 / Math.PI,
  };
}
</code></pre>
<p>Then it's two <code>easeTo</code> calls: dive in before landfall, pull back out before the results appear.</p>
<pre><code class="language-javascript">const before = {
  center: map.getCenter(), zoom: map.getZoom(),
  pitch: map.getPitch(), bearing: map.getBearing(),
};
const cam = shoreCamera(grid, sea, map.getCenter());

map.easeTo({
  center: cam.center,
  zoom: Math.min(13.6, before.zoom + 2.8),
  pitch: 72,
  bearing: cam.bearing,
  duration: 1200,
});

setTimeout(() =&gt; map.easeTo({ ...before, duration: 2600 }), (T_LANDFALL + 3.2) * 1000);
</code></pre>
<p>Here is what those two calls produce. The camera has dropped to a steep pitch above the shore of Odesa and turned to face the Gulf. The sea pulls back first, exposing a wide band of sand, and then the front comes in over the beach and into the port. Everything you see moving is the same flood canvas from Step 3, foreshortened by the camera and draped over the terrain.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/4ba27056-3ff4-4d5a-9472-f0d43bb101b6.gif" alt="Animated: a tilted camera view over the shore of Odesa. The sea first draws back from the beach, exposing sand, then a dark wave front rolls back in across the beach and the port while the city fills the lower half of the frame." style="display: block;" width="720" height="520" loading="lazy">

<p>Notice that nothing in the frame loop knows or cares that the camera moved. The loop keeps writing the same pixels into the same canvas, and the map does the rest. That's what Step 3 bought you.</p>
<h2 id="heading-where-the-ground-layer-stops">Where the Ground Layer Stops</h2>
<p>Everything so far lives on the ground. The flood canvas is the map's own surface, and that's exactly why it works: perspective, rotation and terrain come free. The moment you need something with height, the trick runs out. You can't drape a tower onto a raster.</p>
<p>I learned where that line is the expensive way. I built a real 3D wall of water as a <code>three.js</code> custom layer, and it worked. I also cut it, for a reason worth knowing before you spend the time.</p>
<p>A 30-metre wave seen from 250 metres away covers about 7 degrees of a 37-degree field of view, a fifth of the screen. To make it fill the frame, you have to put the camera a hundred metres from it and nearly on the ground, where satellite imagery smears into mud. The geometry was correct and the shot was bad. Draped water under a pitched camera turned out to read as more water than a correctly-scaled wall did.</p>
<p>So the ground layer stayed a ground layer. But the earthquake scenario had no such escape: a building that collapses has to be an object. That is Part 2.</p>
<h2 id="heading-part-2-things-with-height">Part 2: Things with Height</h2>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/ee831f6b-7f05-4b1b-ac4b-f47152fad5d5.jpg" alt="Street-level view of central Kyiv during a simulated magnitude 7.8 earthquake. Textured high-rise towers stand in the foreground, several of them leaning, and grey dust clouds drift across the scene over the Olympic stadium." style="display: block;" width="1095" height="790" loading="lazy">

<p>For the earthquake scenario, I needed buildings to fall. This half is what I ended up with after roughly ten rounds of rebuilding it: a mix of map-native extrusions for the thousands of buildings that only need to stand there, and a <code>three.js</code> scene rendered into the map's own WebGL context for the ones that come down.</p>
<p>Both paths read the same vector tiles, share the same depth buffer and move together under every camera move.</p>
<h2 id="heading-two-kinds-of-3d-and-why-you-need-both">Two Kinds of 3D, and Why You Need Both</h2>
<p>A <code>fill-extrusion</code> layer is the map engine's own 3D. It's fast, it handles tens of thousands of buildings, it's lit consistently with the rest of the map, and it's driven by data expressions: height from a property, colour from a property, and, the part that matters here, height multiplied by a per-feature <em>state</em> you can change at runtime. What it can't do is move. An extrusion is always a vertical prism standing on the ground.</p>
<p>A <code>custom</code> layer gives you the map's WebGL context and projection matrix every frame and lets you draw whatever you want into it. With <code>three.js</code> on the other end, that means real objects: meshes with position, rotation, and scale, instanced by the thousand, writing into the same depth buffer as the map so that a falling block disappears correctly behind a building that's still standing.</p>
<p>The split that works is simple. <strong>Every building is an extrusion.</strong> When one is damaged, its extrusion shrinks (that's the per-feature state). When one collapses close enough to the camera that you'd see the difference, the extrusion shrinks to nothing and a <code>three.js</code> object takes its place for the two seconds of the fall. Then the object is replaced with a pile of rubble, also <code>three.js</code>, and the frame rate never notices.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/de9747f7-1e42-4923-862b-eb8b2a7d3708.jpg" alt="Pitched view of central Kyiv before the shaking starts. Thousands of buildings are extruded from the map's vector tiles with window-pattern textures on their walls; a 3D model of the Olympic stadium stands in the middle distance." style="display: block;" width="1095" height="790" loading="lazy">

<h2 id="heading-step-8-get-buildings-out-of-the-maps-own-tiles">Step 8: Get Buildings Out of the Map's Own Tiles</h2>
<p>You don't need a building dataset. The map is already downloading one. Mapbox Streets vector tiles carry a <code>building</code> source layer with a polygon footprint, a <code>height</code>, a <code>min_height</code> for buildings that start above ground, and an <code>extrude</code> flag. <code>querySourceFeatures</code> reads whatever is currently loaded:</p>
<pre><code class="language-javascript">function buildingSource(map) {
  const sources = map.getStyle().sources;
  if (sources.composite) return "composite";         // Mapbox styles
  if (sources.openmaptiles) return "openmaptiles";   // MapLibre + OpenMapTiles
  for (const id in sources) if (sources[id].type === "vector") return id;
  return null;
}

function collectBuildings(map, center, kx, ky) {
  const src = buildingSource(map);
  if (!src) return [];
  const feats = map.querySourceFeatures(src, { sourceLayer: "building" });
  const out = [], seen = new Set();

  for (const f of feats) {
    const p = f.properties || {}, g = f.geometry;
    if (!g || p.extrude === "false" || p.underground === "true") continue;

    const polys = g.type === "Polygon" ? [g.coordinates]
                : g.type === "MultiPolygon" ? g.coordinates : null;
    if (!polys || !polys[0] || polys[0][0].length &lt; 4) continue;

    // centroid and bounds of the outer ring
    const ring = polys[0][0], n = ring.length - 1;
    let sx = 0, sy = 0, x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
    for (let j = 0; j &lt; n; j++) {
      const [x, y] = ring[j];
      sx += x; sy += y;
      if (x &lt; x0) x0 = x; if (x &gt; x1) x1 = x;
      if (y &lt; y0) y0 = y; if (y &gt; y1) y1 = y;
    }
    sx /= n; sy /= n;

    // the same building appears once per tile it touches
    const key = sx.toFixed(6) + "," + sy.toFixed(6) + "," + n;
    if (seen.has(key)) continue;
    seen.add(key);

    let h = +(p.height ?? p.render_height);
    if (!(h &gt; 0)) h = 8;                              // no data: assume two storeys
    const mh = Math.min(h, +(p.min_height ?? p.render_min_height) || 0);

    out.push({
      geometry: g, polys, lng: sx, lat: sy, h, mh,
      d: Math.hypot((sx - center.lng) * kx, (sy - center.lat) * ky),   // metres from epicentre
      rf: 0.5 * Math.sqrt(Math.max(4, (x1 - x0) * kx * (y1 - y0) * ky)), // rough radius, metres
    });
  }
  out.sort((a, b) =&gt; a.d - b.d);
  return out.slice(0, 9000);
}
</code></pre>
<p><code>kx</code> and <code>ky</code> are metres per degree of longitude and latitude at the city's latitude: <code>111320 * cos(lat)</code> and <code>110574</code>. Everything downstream works in metres from the epicentre.</p>
<p>Three things to know about this data. First, <code>querySourceFeatures</code> returns a building once for each tile it intersects, so you have to deduplicate. A rounded centroid plus vertex count makes a good key.</p>
<p>Second, the features <strong>have no stable IDs</strong> in Mapbox Streets. That matters enormously in Step 11.</p>
<p>Third, you only get what's loaded, which means you have to zoom in to where the buildings are before you collect them, and wait for the tiles to arrive.</p>
<p>In HazardSim, the camera dives in two steps, holds until <code>map.areTilesLoaded()</code> is true and the feature count stops changing between polls, and only then runs <code>collectBuildings</code>. If you collect too early, you get the ten buildings that happened to be in the first tile.</p>
<h2 id="heading-step-9-make-extrusions-look-like-buildings">Step 9: Make Extrusions Look Like Buildings</h2>
<p>The default extrusion is a flat-shaded box in one colour. It reads as a diagram. The trick that fixes it costs almost nothing: <code>fill-extrusion-pattern</code> takes an image from the style's sprite and tiles it over the walls, and you can add images to the sprite at runtime with <code>map.addImage</code>.</p>
<p>Draw a few façade textures on a canvas (rows of windows on a wall colour, with slight noise so they don't look computer-generated), register them, and pick one per building from its height:</p>
<pre><code class="language-javascript">function makeFacade(map, id, wall, glass) {
  const cv = document.createElement("canvas");
  cv.width = 128; cv.height = 64;
  const c = cv.getContext("2d");
  c.fillStyle = wall; c.fillRect(0, 0, 128, 64);

  // four floors of windows, 16px per floor
  for (let f = 0; f &lt; 4; f++) {
    for (let x = 3; x + 6 &lt;= 128; x += 12) {
      const lit = Math.random() &lt; 0.07;
      c.fillStyle = lit ? "#c6b68c" : glass;
      c.fillRect(x, f * 16 + 3, 6, 9);
    }
  }
  // film grain
  const im = c.getImageData(0, 0, 128, 64), d = im.data;
  for (let i = 0; i &lt; d.length; i += 4) {
    const n = (Math.random() - 0.5) * 12;
    d[i] += n; d[i + 1] += n; d[i + 2] += n;
  }
  map.addImage(id, im);
}

makeFacade(map, "fac-glass",  "#566a78", "#3c4e5c");
makeFacade(map, "fac-light",  "#cdc8be", "#364048");
makeFacade(map, "fac-brick",  "#8a5a44", "#2e2a26");
</code></pre>
<p>Then the layer. Height and base are expressions, and both are multiplied by a feature-state value <code>k</code> that defaults to 1. That multiplier is the whole collapse mechanism, so it goes in now:</p>
<pre><code class="language-javascript">const H  = ["coalesce", ["get", "height"], ["get", "render_height"], 8];
const MH = ["coalesce", ["get", "min_height"], ["get", "render_min_height"], 0];
const K  = ["coalesce", ["feature-state", "k"], 1];

function addBuildingLayers(map, source, sourceLayer, before) {
  const common = { type: "fill-extrusion", source, minzoom: 13 };
  if (sourceLayer) {
    common["source-layer"] = sourceLayer;
    common.filter = ["all", ["!=", ["get", "extrude"], "false"], ["!=", ["get", "underground"], "true"]];
  }
  map.addLayer({
    ...common, id: "bld-walls",
    paint: {
      "fill-extrusion-pattern": ["case",
        ["&gt;=", H, 45], "fac-glass",
        ["&gt;=", H, 14], "fac-light",
        "fac-brick"],
      "fill-extrusion-height": ["*", H, K],
      "fill-extrusion-base":   ["*", MH, K],
      "fill-extrusion-opacity": 1,
    },
  }, before);
  // a thin second extrusion on top gives the roof its own texture
  map.addLayer({
    ...common, id: "bld-roof",
    paint: {
      "fill-extrusion-pattern": "fac-roof",
      "fill-extrusion-height": ["+", ["*", H, K], 0.05],
      "fill-extrusion-base":   ["max", ["*", MH, K], ["-", ["*", H, K], 0.45]],
      "fill-extrusion-opacity": 1,
    },
  }, before);
}
</code></pre>
<p><code>before</code> should be the ID of the first <code>symbol</code> layer in the style, so the buildings go under the labels. Find it with a loop over <code>map.getStyle().layers</code>.</p>
<p>A pattern can't be rotated or scaled per feature, so windows don't line up with floors exactly. At the camera heights this runs at, nobody can tell.</p>
<h2 id="heading-step-10-decide-what-falls">Step 10: Decide What Falls</h2>
<p>Now the simulation part, which is short. For each building, you need the shaking intensity at its location and the probability that a building of that type collapses at that intensity.</p>
<p>Shaking is expressed on the Modified Mercalli scale, I to XII. A standard attenuation relation gives intensity from magnitude <code>M</code> and distance <code>r</code> in kilometres (<code>depth</code> is the hypocentre depth, 10 km for a shallow crustal quake):</p>
<pre><code class="language-javascript">const DEPTH_KM = 10;

function mmiAt(M, rKm) {
  const R = Math.sqrt(rKm * rKm + DEPTH_KM * DEPTH_KM);
  const v = 1.5 * M - 3.0 * Math.log10(R) - 0.0018 * R + 1.6;
  return Math.max(0, Math.min(12, v));
}
</code></pre>
<p>Collapse probability as a function of intensity is a fragility curve. The published ones are per building class and far more detailed than a simulation needs. This piecewise-linear version is tuned to look right and to give sane casualty numbers. Multiply it by a factor for construction quality and another for height. Mid-rise buildings fare worst, very tall ones are engineered and fare better:</p>
<pre><code class="language-javascript">const FRAG = [[6.5, 0], [7, 0.004], [8, 0.025], [9, 0.08], [10, 0.2], [11, 0.38], [12, 0.55]];
const QUALITY = { strict: 0.2, avg: 1, poor: 3 };

function collapseProbability(mmi) {
  if (mmi &lt;= FRAG[0][0]) return 0;
  for (let i = 1; i &lt; FRAG.length; i++) {
    if (mmi &lt;= FRAG[i][0]) {
      const [m0, p0] = FRAG[i - 1], [m1, p1] = FRAG[i];
      return p0 + (p1 - p0) * (mmi - m0) / (m1 - m0);
    }
  }
  return FRAG[FRAG.length - 1][1];
}

function assignDamage(buildings, M, epicentre, quality) {
  const kx = 111320 * Math.cos(epicentre.lat * Math.PI / 180), ky = 110574;
  const q = QUALITY[quality] || 1;

  for (const b of buildings) {
    const rKm = Math.hypot((b.lng - epicentre.lng) * kx, (b.lat - epicentre.lat) * ky) / 1000;
    const mmi = mmiAt(M, rKm);
    const hf = b.h &lt; 5 ? 0.7 : b.h &lt; 35 ? 1.15 : b.h &lt; 70 ? 0.8 : 0.45;
    const pCollapse = Math.min(0.9, collapseProbability(mmi) * q * hf);
    const pDamage = mmi &gt;= 6 ? Math.min(0.6, pCollapse * 2.5 + 0.004) : 0;

    const r = Math.random();
    b.cat = r &lt; pCollapse ? 2 : r &lt; pCollapse + pDamage ? 1 : 0;   // 2 collapse, 1 damaged, 0 fine
    b.start = 0.8 + Math.random() * 2.8;                            // seconds after the shock
  }
}
</code></pre>
<p>The per-building randomness is what sells it. Two identical towers next to each other, one falls and one stands. That's also how real earthquakes look.</p>
<h2 id="heading-step-11-animate-collapse-without-rebuilding-layers">Step 11: Animate Collapse Without Rebuilding Layers</h2>
<p>Here's the mechanism from Step 9 paying off. Each frame, for every building that's falling, set its feature-state <code>k</code> to a number between 1 and its final rubble height. The extrusion shrinks. No layer is rebuilt, no GeoJSON is re-set, and no tiles are re-parsed.</p>
<pre><code class="language-javascript">map.setFeatureState({ source: "bld", id: b.id }, { k: 0.62 });
</code></pre>
<p>There's one catch, and it's the one that cost me the most time in this whole project: <code>setFeatureState</code> <strong>needs a feature ID, and Mapbox Streets buildings don't have one.</strong> Calling it against the vector source silently does nothing.</p>
<p>The fix is to copy the buildings you collected into your own GeoJSON source, with an <code>id</code> you control, and tell the source to promote that property to the feature ID:</p>
<pre><code class="language-javascript">const feats = buildings.map((b, i) =&gt; {
  b.id = i;
  return { type: "Feature", properties: { i, height: b.h, min_height: b.mh }, geometry: b.geometry };
});

map.addSource("bld", {
  type: "geojson",
  data: { type: "FeatureCollection", features: feats },
  promoteId: "i",
  maxzoom: 16,
});
addBuildingLayers(map, "bld", null, firstSymbolLayer);
</code></pre>
<p>Now <code>setFeatureState({ source: "bld", id: 17 }, ...)</code> reaches building 17. Keep the original tile-backed layers around until the GeoJSON source reports <code>isSourceLoaded</code>, then remove them, so there's no frame where the city blinks.</p>
<p>The shape of <code>k</code> over time is what makes a collapse look like a collapse rather than a building sliding into the ground. I ended up with five modes, chosen at random per building and constrained by height:</p>
<pre><code class="language-javascript">// k0 = starting height multiplier (1), kf = final rubble height, u = progress 0..1
function collapseK(b, u) {
  const k0 = b.k0, sp = k0 - b.kf;
  switch (b.mode) {
    case 1: {   // floor by floor: ns steps, each with a fast drop then a pause
      const s = u * b.ns, i = Math.min(b.ns - 1, Math.floor(s));
      let f = s - i;
      f = f &lt; 0.45 ? f * f / 0.45 * 1.1 : 0.55 + (f - 0.45) * 0.45 / 0.55;
      return k0 - sp * Math.min(1, (i + Math.min(1, f)) / b.ns);
    }
    case 2: {   // soft storey: ground floor gives, building drops one floor, pauses, then goes
      const sd = Math.min(sp * 0.5, 3.2 / b.h);
      if (u &lt; 0.12) return k0 - sd * (u / 0.12) ** 2;
      if (u &lt; 0.5)  return k0 - sd;
      const v = (u - 0.5) / 0.5;
      return k0 - sd - (sp - sd) * v * v;
    }
    case 3: {   // crushed top: upper part fails first
      const pt = sp * 0.45;
      if (u &lt; 0.3)  return k0 - pt * (u / 0.3) ** 2;
      if (u &lt; 0.55) return k0 - pt;
      const v = (u - 0.55) / 0.45;
      return k0 - pt - (sp - pt) * v * v;
    }
    case 4:     // sideways: steady, slightly accelerating
      return k0 - sp * Math.pow(u, 1.6);
    default:    // pancake: accelerating free fall
      return k0 - sp * u * u;
  }
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/090f37e2-11d6-41cd-ae23-0affa8357364.png" alt="Line chart of remaining height against progress for the five collapse modes. Pancake is a smooth accelerating curve. Floor-by-floor is a staircase of drops and pauses. Soft storey drops a little, holds flat for a long time, then falls. Crushed top drops early, holds, then falls. Sideways is a gentle curve. All five meet at the same final height." style="display: block;" width="1400" height="700" loading="lazy">

<p>The frame loop is then a few lines per building:</p>
<pre><code class="language-javascript">function frame(now) {
  const el = (now - T0) / 1000, dt = Math.min(0.04, (now - last) / 1000);
  last = now;

  for (const b of active) {
    if (b.done || el &lt; b.start) continue;
    const u = Math.min(1, (el - b.start) / b.dur);
    const k = collapseK(b, u);
    map.setFeatureState({ source: "bld", id: b.id }, { k });
    if (u &gt;= 1) { b.done = true; onLanded(b); }
  }
  requestAnimationFrame(frame);
}
</code></pre>
<p>For a damaged-but-standing building (<code>cat === 1</code>), <code>kf</code> is close to 1 and the mode is a short settle: the building visibly drops half a metre and stops. It's a small detail, and it's the one that makes the whole street look hit rather than just the buildings that fell.</p>
<p>Clamp <code>dt</code> to 40 ms. If the tab stutters and a frame takes a quarter of a second, a building that was mid-fall would jump instead of fall, and the eye catches that instantly.</p>
<h2 id="heading-step-12-a-threejs-scene-inside-the-map">Step 12: A Three.js Scene Inside the Map</h2>
<p>Shrinking extrusions handle the buildings in the distance. For the ones near the camera, you want to see the structure break: a tower tipping over and snapping into blocks, debris arcing out from the base, or rubble left on the street. That needs objects, so this is where <code>three.js</code> comes in.</p>
<p>The custom layer gets two callbacks: <code>onAdd</code> once, with the map and its GL context, and <code>render</code> every frame, with the context and the map's projection matrix. The non-obvious part is coordinates. You want to work in metres from an origin, not in Mercator units, so build a matrix that converts, and multiply it into the map's projection each frame:</p>
<pre><code class="language-javascript">function makeScene(map, origin, before) {
  const mc = mapboxgl.MercatorCoordinate.fromLngLat([origin.lng, origin.lat], 0);
  const s = mc.meterInMercatorCoordinateUnits();
  // metres east / north / up at the origin  -&gt;  Mercator.  Mercator y grows southward, hence -s.
  const toMercator = new THREE.Matrix4()
    .makeTranslation(mc.x, mc.y, mc.z)
    .scale(new THREE.Vector3(s, -s, s));

  const scene = new THREE.Scene();
  const camera = new THREE.Camera();
  scene.add(new THREE.HemisphereLight(0xfff4e4, 0x3c342d, 0.55));
  scene.add(new THREE.AmbientLight(0xffffff, 0.1));
  const sun = new THREE.DirectionalLight(0xfff8ee, 0.8);
  sun.position.set(-0.45, -0.6, 1);
  scene.add(sun);

  let renderer = null;
  const layer = {
    id: "debris3d",
    type: "custom",
    renderingMode: "3d",
    onAdd(m, gl) {
      renderer = new THREE.WebGLRenderer({ canvas: m.getCanvas(), context: gl, antialias: true });
      renderer.autoClear = false;             // the map has already drawn this frame
      renderer.localClippingEnabled = true;   // used to sink buildings below ground
    },
    render(gl, matrix) {
      camera.projectionMatrix.fromArray(matrix).multiply(toMercator);
      renderer.resetState();                  // Mapbox changed GL state since our last draw
      renderer.render(scene, camera);
    },
  };
  map.addLayer(layer, before);
  return { scene, camera, layer };
}
</code></pre>
<p>On MapLibre, the second argument of <code>render</code> is an object, and the matrix is at <code>args.defaultProjectionData.mainMatrix</code>. Everything else is the same.</p>
<p><code>renderingMode: "3d"</code> is what makes the map share its depth buffer with you. A block of concrete that lands behind a standing extrusion is hidden by it, which is the entire reason to render into the map's context rather than in a separate canvas on top.</p>
<p>Thousands of debris pieces means instancing. HazardSim keeps a pool of <code>InstancedMesh</code> objects, one per kind of piece (slabs, wall fragments, rebar, rocks, roof prisms), each with a fixed capacity, and hands out instance indices as pieces are created:</p>
<pre><code class="language-javascript">function makePool(scene, geometry, material, capacity) {
  const mesh = new THREE.InstancedMesh(geometry, material, capacity);
  // allocate the colour buffer for the full capacity up front (see Gotchas)
  mesh.instanceColor = new THREE.InstancedBufferAttribute(new Float32Array(capacity * 3).fill(1), 3);
  mesh.count = 0;
  mesh.frustumCulled = false;                 // the map camera is not a three.js camera
  mesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
  scene.add(mesh);

  const dummy = new THREE.Object3D(), color = new THREE.Color();
  dummy.rotation.order = "ZXY";
  return {
    n: 0, capacity,
    add(p) {
      if (this.n &gt;= capacity) return -1;
      const i = this.n++;
      this.set(i, p);
      color.setRGB(p.rgb[0], p.rgb[1], p.rgb[2]);
      mesh.setColorAt(i, color);
      mesh.instanceColor.needsUpdate = true;
      mesh.count = this.n;
      return i;
    },
    set(i, p) {
      dummy.position.set(p.x, p.y, p.z);
      dummy.rotation.set(p.tx, p.ty, p.yaw);
      dummy.scale.set(p.sx, p.sy, p.sz);
      dummy.updateMatrix();
      mesh.setMatrixAt(i, dummy.matrix);
      mesh.instanceMatrix.needsUpdate = true;
    },
  };
}

const concrete = new THREE.MeshStandardMaterial({ map: concreteTexture, roughness: 1 });
const pools = {
  slab: makePool(scene, new THREE.BoxGeometry(1, 1, 1), concrete, 30000),
  wall: makePool(scene, new THREE.BoxGeometry(1, 1, 1), facadeMaterial, 1500),
  bar:  makePool(scene, new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x6e4c38, metalness: 0.25 }), 20000),
  rock: makePool(scene, rockGeometry(), concrete, 9000),
};
</code></pre>
<p>Thirty thousand slabs sounds like a lot, but it's one draw call.</p>
<p>One more thing the map needs from you: it only redraws when something changes. Your scene changing is not, from the map's point of view, something changing. Call <code>map.triggerRepaint()</code> at the end of every frame in which you moved anything, or your meshes will update in memory and never on screen.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/8481687c-e9b9-48f7-846b-0520afbda6ed.jpg" alt="Pitched close-up of a Kyiv street. Several textured high-rise towers rebuilt as three.js models stand among the extruded buildings, ready for the shaking to start; the Olympic stadium model is in the background." style="display: block;" width="1095" height="790" loading="lazy">

<h2 id="heading-step-13-from-footprint-to-a-box-that-tips-over">Step 13: From Footprint to a Box That Tips Over</h2>
<p>The vector tile gives you a footprint polygon. To tip a building over, you need a box: a centre, an orientation, and two side lengths. The oriented bounding box is a few lines:</p>
<pre><code class="language-javascript">function orientedBox(ring, kx, ky, origin) {
  // ring in lng/lat -&gt; local metres
  const loc = ring.map(([lng, lat]) =&gt; [(lng - origin.lng) * kx, (lat - origin.lat) * ky]);

  // the longest edge sets the orientation
  let ang = 0, best = 0;
  for (let i = 1; i &lt; loc.length; i++) {
    const ex = loc[i][0] - loc[i - 1][0], ey = loc[i][1] - loc[i - 1][1];
    if (ex * ex + ey * ey &gt; best) { best = ex * ex + ey * ey; ang = Math.atan2(ey, ex); }
  }

  // project every vertex onto that axis and its normal, take the extents
  const ca = Math.cos(ang), sa = Math.sin(ang);
  let u0 = Infinity, u1 = -Infinity, v0 = Infinity, v1 = -Infinity;
  for (const [x, y] of loc) {
    const u = x * ca + y * sa, v = -x * sa + y * ca;
    if (u &lt; u0) u0 = u; if (u &gt; u1) u1 = u;
    if (v &lt; v0) v0 = v; if (v &gt; v1) v1 = v;
  }
  const cu = (u0 + u1) / 2, cv = (v0 + v1) / 2;
  return {
    x: cu * ca - cv * sa, y: cu * sa + cv * ca,    // centre, metres from origin
    ang,
    L1: Math.max(2, u1 - u0), L2: Math.max(2, v1 - v0),
  };
}
</code></pre>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/28644ba8-6900-4885-98f6-ca163d50aa6c.png" alt="Three-panel diagram. First: a building footprint polygon with its longest edge highlighted, labelled &quot;longest edge gives the angle&quot;. Second: the polygon rotated to that angle with an orange bounding rectangle around it, labelled &quot;L1 by L2, centre, angle&quot;. Third: a stack of four blocks hinged at the bottom edge, with the formula theta double-prime equals 1.5 g over h times sine theta." style="display: block;" width="2800" height="1120" loading="lazy">

<p>The box becomes a stack of two to four blocks, one <code>Mesh</code> each, in a <code>Group</code> whose origin is on the bottom edge the building will rotate around. The physics is a rigid body falling over: angular acceleration proportional to <code>g / h · sin θ</code>, with a small initial nudge so it starts moving. When the lean passes a threshold, the upper blocks detach and fly ballistically with the velocity they had at that instant:</p>
<pre><code class="language-javascript">function startTip(scene, box, h, onLand) {
  const n = Math.max(2, Math.min(4, Math.round(h / 9))), hs = h / n;
  const geo = new THREE.BoxGeometry(box.L1, box.L2, hs);
  const group = new THREE.Group();
  group.position.set(box.x + Math.cos(box.ang) * box.L1 / 2, box.y + Math.sin(box.ang) * box.L1 / 2, 0);
  group.rotation.z = box.ang;
  scene.add(group);

  const segs = [];
  for (let i = 0; i &lt; n; i++) {
    const m = new THREE.Mesh(geo, wallMaterial);
    m.frustumCulled = false;
    group.add(m);
    segs.push({ m, free: false, gone: false, x: -box.L1 / 2, z: hs * (i + 0.5), th: 0, px: 0, pz: 0 });
  }

  const tip = { th: 0.03, w: 0.22, broke: false, bend: 0.1 + Math.random() * 0.14, brk: 0.4 + Math.random() * 0.3 };

  function pose() {
    let bx = -box.L1 / 2, bz = 0;
    for (let j = 0; j &lt; n; j++) {
      const s = segs[j];
      if (s.free) continue;
      const th = tip.th * (1 + tip.bend * j);        // upper blocks bend a little further
      const sn = Math.sin(th), cs = Math.cos(th);
      if (j === 0) { bx = -box.L1 / 2 * cs; bz = box.L1 / 2 * sn; }
      s.px = s.x; s.pz = s.z;
      s.x = bx + sn * hs / 2; s.z = bz + cs * hs / 2; s.th = th;
      bx += sn * hs; bz += cs * hs;
      s.m.position.set(s.x, 0, s.z);
      s.m.rotation.y = th;
    }
  }

  return function tick(dt) {
    tip.w = Math.min(2.2, tip.w + 1.5 * 9.8 / h * Math.sin(tip.th) * dt);
    tip.th += Math.min(0.09, tip.w * dt);          // never more than ~5 degrees per frame
    pose();

    if (!tip.broke &amp;&amp; tip.th * (1 + tip.bend * (n - 1)) &gt; tip.brk &amp;&amp; n &gt; 1) {
      tip.broke = true;
      for (let j = 1; j &lt; n; j++) {
        const s = segs[j];
        s.free = true;
        s.vx = Math.max(-18, Math.min(18, (s.x - s.px) / Math.max(dt, 0.008)));
        s.vz = Math.max(-18, Math.min(18, (s.z - s.pz) / Math.max(dt, 0.008)));
        s.w = tip.w * (1 + tip.bend * j) * (1.05 + Math.random() * 0.25);
      }
    }

    let left = 0;
    for (const s of segs) {
      if (s.gone) continue;
      if (s.free) {
        s.vz -= 9.8 * dt; s.x += s.vx * dt; s.z += s.vz * dt; s.th += s.w * dt;
        s.m.position.set(s.x, 0, s.z);
        s.m.rotation.y = s.th;
      }
      const landed = s.free ? s.z &lt; Math.min(hs, box.L1) * 0.5 + 0.3 : tip.th &gt;= 1.25;
      if (landed) {
        s.gone = true;
        group.remove(s.m);
        onLand(group.position.x + Math.cos(box.ang) * s.x, group.position.y + Math.sin(box.ang) * s.x);
      } else left++;
    }
    if (!left) { scene.remove(group); geo.dispose(); return true; }   // finished
    return false;
  };
}
</code></pre>
<p>The clamps aren't decoration. Velocity at detachment is limited to 18 m/s and the frame step <code>dt</code> to a minimum of 8 ms, because the velocity is computed from a position difference, and a hiccup frame would otherwise launch a block into orbit. Angular velocity is limited to 2.5 rad/s and the lean to 0.09 rad per frame for the same reason. Every one of those numbers was added after watching a building do something a building can't do.</p>
<p><code>onLand</code> is where a collapse starts to look like one: each block that hits the ground spawns a burst of debris and dust at that point, and leaves a pile.</p>
<h2 id="heading-step-14-debris-and-dust">Step 14: Debris and Dust</h2>
<p>Debris is the instanced pools from Step 12 plus gravity. When a collapsing building passes a milestone (the first drop, each floor in floor-by-floor mode, a block landing), throw a handful of pieces out from the edges of the footprint, with velocity pointing away from the centre:</p>
<pre><code class="language-javascript">function throwDebris(pools, b, origin, kx, ky, top, n) {
  const ring = b.polys[0][0];
  const cx = (b.lng - origin.lng) * kx, cy = (b.lat - origin.lat) * ky;
  for (let i = 0; i &lt; n; i++) {
    // a random point on a random edge of the footprint
    const e = 1 + Math.floor(Math.random() * (ring.length - 1)), t = Math.random();
    const a = ring[e - 1], z = ring[e];
    const x = ((a[0] + (z[0] - a[0]) * t) - origin.lng) * kx;
    const y = ((a[1] + (z[1] - a[1]) * t) - origin.lat) * ky;
    // outward, with a little spread
    const ox = x - cx, oy = y - cy, ol = Math.hypot(ox, oy) || 1, v = 2 + Math.random() * 6;
    const size = 0.3 + Math.random() * 1.1;
    const idx = pools.rock.add({
      x, y, z: top * (0.35 + Math.random() * 0.65),
      yaw: Math.random() * 6, tx: Math.random() * 6, ty: Math.random() * 6,
      sx: size, sy: size * 0.8, sz: size * 0.6, rgb: concreteColour(),
    });
    if (idx &gt;= 0) flying.push({ idx, x, y, z: top, vx: ox / ol * v, vy: oy / ol * v, vz: Math.random() * 3, spin: (Math.random() - 0.5) * 8 });
  }
}

function tickDebris(pools, dt) {
  for (let i = flying.length - 1; i &gt;= 0; i--) {
    const p = flying[i];
    p.vz -= 9.8 * dt;
    p.x += p.vx * dt; p.y += p.vy * dt; p.z += p.vz * dt;
    p.tx += p.spin * dt;
    if (p.z &lt;= p.sz * 0.35) { p.z = p.sz * 0.35; flying.splice(i, 1); }   // landed: stays as rubble
    pools.rock.set(p.idx, p);
  }
}
</code></pre>
<p>Pieces that land simply stop being updated and stay in the pool. That's your rubble, for free.</p>
<p>HazardSim adds a few more things on top: stacked floor slabs on a 9-metre grid where a building stood, wall fragments with windows, bent rebar, a low fill-extrusion mound under the pile so the ground isn't flat, and for the closest buildings, a set of photogrammetry-scanned rubble models. Those are polish, and the pool plus gravity gets you most of the way.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/1544d432-3f78-480b-9412-fa4d0fa73e82.jpg" alt="Close-up at street level after the collapse. Dust hangs over a block of towers, the ground between them is strewn with grey rubble, and the sky is a haze of smoke lit from the side." style="display: block;" width="1095" height="790" loading="lazy">

<p>Dust is the one place where I draw in screen space, and it's worth saying why that's fine here when it was fatal for water in Part 1. Dust particles are small, there are hundreds of them, and each lives three to eight seconds. They're also drawn as soft sprites with per-particle position, size, and rotation projected from a map point each frame. There are no edges to see and nothing to line up with. The screen-space rule is about large, persistent things with shape.</p>
<p>The important decision is <strong>where dust comes from</strong>. Early versions had a constant haze over the city and burning fires, and it looked like a screensaver. What reads as real is dust that comes only from events: a puff when a floor drops, a surge along the ground when a building lands, a jet from the ground floor of a soft-storey collapse. Each event emits a burst with a size proportional to the building's footprint and a vertical speed proportional to the drop, then nothing until the next event.</p>
<pre><code class="language-javascript">function emitDust(b, level, n, surge) {
  for (let i = 0; i &lt; n &amp;&amp; dust.length &lt; MAX_DUST; i++) {
    const a = Math.random() * Math.PI * 2;
    const speed = surge ? 5 + Math.random() * 8 : 1 + Math.random() * 3;
    dust.push({
      lng: b.lng, lat: b.lat,                                        // anchor on the map
      x: Math.cos(a) * b.rf * 0.6, y: Math.sin(a) * b.rf * 0.6,     // offset, metres
      z: surge ? Math.random() * 5 : level * (0.2 + Math.random() * 0.8),
      vx: Math.cos(a) * speed, vy: Math.sin(a) * speed,
      vz: surge ? 0.3 + Math.random() * 1.2 : 1.5 + Math.random() * 3,
      size: (surge ? b.rf * 0.5 + 6 : b.rf * 0.6 + 4) * (0.7 + Math.random() * 0.6),
      grow: 3 + Math.random() * 5,
      t: 0, life: (surge ? 5 : 3.5) + Math.random() * 2.5,
      sprite: sprites[Math.floor(Math.random() * sprites.length)],
      alpha: 0.5 + Math.random() * 0.3,
    });
  }
}
</code></pre>
<p>Per frame, each particle decelerates, drifts with the wind, grows, and is projected: <code>map.project([lng + x / kx, lat + y / ky])</code> gives the screen position of its ground point, and the height is applied as <code>y -= z * pixelsPerMetre * sin(pitch)</code>. Sort by screen depth, draw back to front with <code>drawImage</code>, and fade with age. It's a few hundred <code>drawImage</code> calls per frame on a 2D canvas over the map, and it costs almost nothing.</p>
<h2 id="heading-step-15-the-camera-has-to-shake">Step 15: The Camera Has to Shake</h2>
<p>Everything so far could be running silently in a corner of the screen. What makes a viewer feel the earthquake is the camera.</p>
<p>Two things. First, the dive: from the overview, ease to zoom 14.6 at 45 degrees, hold until tiles are loaded, then ease to zoom 16.2 at 62 degrees over the epicentre. The hold isn't optional. If you dive straight to zoom 16, the vector tiles for that zoom haven't arrived, <code>querySourceFeatures</code> returns almost nothing, and the earthquake hits an empty city.</p>
<pre><code class="language-javascript">function diveToCity(map, center, then) {
  const bearing = map.getBearing();
  map.easeTo({ center, zoom: 14.6, pitch: 45, bearing: bearing - 10, duration: 1100, essential: true });
  const t1 = Date.now();
  (function hold() {
    const loaded = !map.isMoving() &amp;&amp; map.areTilesLoaded();
    if (Date.now() - t1 &gt; 1000 &amp;&amp; (loaded || Date.now() - t1 &gt; 2000)) {
      map.easeTo({ center, zoom: 16.2, pitch: 62, bearing: bearing - 25, duration: 1500, essential: true });
      map.once("moveend", then);
    } else setTimeout(hold, 150);
  })();
}
</code></pre>
<p>Second, the shake. Don't move the map camera for this. A camera that jitters through <code>easeTo</code> fights the animation system and loads tiles for every jitter. Shake the <em>container</em> with a CSS transform. The map doesn't know it moved:</p>
<pre><code class="language-javascript">function shake(durationMs, magnitude) {
  const el = map.getContainer();
  const w = window.innerWidth, h = window.innerHeight;
  const amp = Math.min(28, w * 0.02, Math.max(6, (magnitude - 4) * 4.2));
  const dir = Math.random() * Math.PI;
  const t0 = performance.now();
  let last = t0, phase = 0;

  function tick(now) {
    const k = (now - t0) / durationMs;
    if (k &gt;= 1) { el.style.transform = ""; return; }
    const dt = Math.min(0.05, (now - last) / 1000); last = now;

    // builds up over the first third, then decays; frequency rises with it
    let env, omega;
    if (k &lt; 0.35) { const u = k / 0.35; env = 0.15 + 0.85 * u * u * (3 - 2 * u); omega = 7 + 39 * u * u; }
    else          { const v = (k - 0.35) / 0.65; env = Math.pow(1 - v, 1.4); omega = 46 - 18 * v; }
    phase += omega * dt;

    const a = amp * env;
    const osc = Math.sin(phase) * 0.78 + (Math.random() - 0.5) * 0.44 * Math.min(1, omega / 30);
    const x = Math.cos(dir) * osc * a, y = Math.sin(dir) * osc * a * 0.7;
    el.style.transform = `translate(${x.toFixed(1)}px, ${y.toFixed(1)}px) rotate(${(osc * a * 0.012).toFixed(3)}deg) scale(${(1 + 2.4 * amp / Math.min(w, h) * env).toFixed(4)})`;
    requestAnimationFrame(tick);
  }
  requestAnimationFrame(tick);
}
</code></pre>
<p>The envelope matters more than the amplitude. Real shaking builds for a second or two, peaks, and dies off over several more, with the frequency rising as it builds. A constant jitter reads as a broken video. An aftershock at about half the amplitude, three or four seconds after the main shock, finishes the effect.</p>
<p>When the shaking stops, ease the camera down to the centre of the nearest collapses and hold for a few seconds so the rubble gets its moment, then pull back up to the intensity rings and the casualty figures.</p>
<h2 id="heading-keeping-it-fast">Keeping It Fast</h2>
<p>A few decisions kept this at 60 fps on a laptop and usable on phones.</p>
<h3 id="heading-1-pools-with-fixed-capacity">1. Pools with Fixed Capacity</h3>
<p>Every instanced pool has a cap, and <code>add</code> returns <code>-1</code> when it's full. The caps scale down for low-power devices: 9,000 slabs instead of 30,000, 3,000 rocks instead of 9,000. The scene degrades to fewer pieces rather than to a slideshow.</p>
<h3 id="heading-2-a-device-tier-decided-once">2. A Device Tier, Decided Once</h3>
<p>Mobile user agent, <code>navigator.deviceMemory &lt; 6</code>, <code>hardwareConcurrency &lt;= 4</code>, or a short screen side under 700 px puts the device in the low tier. The low tier skips the <code>three.js</code> tipping entirely and uses only shrinking extrusions, caps dust at a third, and drops the hero models.</p>
<h3 id="heading-3-rebuild-the-rubble-mound-at-most-every-12-seconds">3. Rebuild the Rubble Mound at Most Every 1.2 Seconds</h3>
<p>The low <code>fill-extrusion</code> mound under each pile is a GeoJSON source, and <code>setData</code> on a GeoJSON source re-parses it. Doing that once per collapsed building was the main cause of stutter in early versions. Now landed buildings go into a pending list that's flushed on a timer.</p>
<h3 id="heading-4-never-remove-a-collapsed-building-from-the-source">4. Never Remove a Collapsed Building from the Source</h3>
<p>It stays in <code>bld</code> with <code>k</code> set to 0.001. Removing features means <code>setData</code>, and <code>setData</code> means a stall.</p>
<h3 id="heading-5-load-assets-on-intent">5. Load Assets on Intent</h3>
<p>The textures and models for the full-detail mode add up to 24 MB. They start downloading when the visitor clicks the earthquake tab, not on page load, and only in the full tier.</p>
<h2 id="heading-what-went-wrong-and-why">What Went Wrong, and Why</h2>
<p>Each of these cost me real time, and the first two are why Part 1 exists at all.</p>
<h3 id="heading-the-sticker-problem">The Sticker Problem</h3>
<p>My first version of a "wall of water" was a video clip drawn on a screen-space canvas, positioned by projecting a map point each frame. On a 13-inch laptop it almost worked. On a 4K monitor it was a rectangle with soft edges hovering over the city, obviously not part of the scene.</p>
<p>No amount of tuning opacity, feathering, or size fixes this, because the problem isn't the sprite. A sprite has no place in a 3D world. Everything in Steps 3 to 6 is the alternative.</p>
<p>If you do need screen-space elements, say a splash sprite anchored to a point, keep them small, short-lived, and numerous, and accept that they'll never carry the shot.</p>
<h3 id="heading-i-couldnt-find-my-layer-twice">I Couldn't Find My Layer, Twice</h3>
<p>The 3D water wall from the end of Part 1 rendered without an error, the mesh moved exactly where my debug probe said it should, and nothing appeared on screen. I'd added it with <code>map.addLayer(layer, "flood")</code>, which inserts it <em>below</em> the flood raster, and the opaque water was hiding my wall. Check <code>map.getStyle().layers</code> before you check anything else.</p>
<p>The second time I lost a layer, it was the opposite problem: it wasn't there at all. <code>map.getStyle().layers</code> doesn't list custom layers. Check with <code>map.getLayer("debris3d")</code> instead. I spent a while convinced the layer wasn't being added.</p>
<h3 id="heading-24-levels-of-transparency">24 Levels of Transparency</h3>
<p>I built sprite sheets with soft alpha edges and ran them through <code>PIL.Image.quantize()</code> to shrink the PNG. The palette compression quantized the alpha channel along with the colours. 256 levels became 24, the smooth falloff became a staircase, and every step was a hard straight edge that looked exactly like a tile boundary. I spent two rounds hunting for a tiling bug that didn't exist.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/bba497b2-fe0e-4398-a7af-40a4245674f1.png" alt="Two versions of the same smoke sprite on a dark background. Left, after palette quantization: the zoomed edge is made of blocky pixels in only a few shades, and the alpha histogram shows eight isolated spikes. Right, full 8-bit alpha: the zoomed edge fades smoothly, and the histogram is a continuous spread of 253 levels." style="display: block;" width="1400" height="1000" loading="lazy">

<p>The fix was to stop quantizing and make the RGB channels constant (the sprites were white anyway), so PNG compression had nothing left to do. The file got three times smaller. I now check alpha with a histogram instead of trusting my eyes.</p>
<h3 id="heading-same-filename-different-file">Same Filename, Different File</h3>
<p>I re-encoded <code>flood.webm</code> with a different grade and redeployed. Visitors kept getting the old one for hours. The CDN cached by URL, and a <code>?v=2</code> query string didn't bust it for a file that already existed.</p>
<p>Renaming the file to <code>flood2.webm</code> fixed it in one deploy. Since then I rename every binary asset I update instead of versioning the URL.</p>
<h3 id="heading-headless-screenshots-lied-twice">Headless Screenshots Lied, Twice</h3>
<p>I tested under headless Chrome with a software GL renderer. Each screenshot took a second or two to capture, so a "sequence" of frames was nothing of the sort, and I spent an afternoon tuning timings against noise.</p>
<p>Two things fixed it: record the browser session as video and cut frames with ffmpeg, and, for colour, read the simulation canvas directly with <code>getImageData</code> instead of measuring the composited screen. The second one sounds obvious written down, but it took me an afternoon to arrive at it.</p>
<p>The same headless setup fooled me again on the earthquake. Satellite tiles load slowly there, and for a long time I thought my building layer was broken because screenshots showed a black city. It was the base map that hadn't arrived. If a layer looks wrong in headless tests, wait for <code>map.areTilesLoaded()</code> before trusting the screenshot.</p>
<h3 id="heading-nothing-happened-when-i-set-feature-state">Nothing Happened When I Set Feature State</h3>
<p><code>setFeatureState</code> against the tile source did nothing and reported nothing, because the features have no IDs. The fix is the GeoJSON copy with <code>promoteId</code> from Step 11. It took me an embarrassingly long time to find, because the API doesn't fail. It just doesn't do anything.</p>
<h3 id="heading-every-instance-was-black">Every Instance Was Black</h3>
<p><code>InstancedMesh.setColorAt</code> in three r128 lazily creates the colour buffer the first time you call it, sized to the mesh's <strong>current</strong> <code>count</code>. My pools started with <code>count = 0</code>, so the buffer was created with zero entries, and every piece rendered black. Allocate <code>instanceColor</code> yourself, for the full capacity, before the first <code>setColorAt</code>. That's the line in <code>makePool</code>.</p>
<h3 id="heading-half-the-debris-vanished-when-i-panned">Half the Debris Vanished When I Panned</h3>
<p><code>three.js</code> frustum-culls meshes against its own camera. Our camera is a bare <code>THREE.Camera</code> with a projection matrix stuffed into it each frame and no idea where the map is looking, so its idea of the frustum is nonsense. Set <code>frustumCulled = false</code> on every mesh in the custom layer.</p>
<h3 id="heading-the-scene-updated-but-the-screen-didnt">The Scene Updated But the Screen Didn't</h3>
<p>The map only repaints when it thinks something changed. Call <code>map.triggerRepaint()</code> after you move your objects. Without it the animation runs at whatever rate the map happens to repaint for other reasons, which in a still scene is zero.</p>
<h3 id="heading-a-sky-made-everything-disappear">A Sky Made Everything Disappear</h3>
<p>On a different project with the same setup, <code>map.setSky(...)</code> hid the whole <code>three.js</code> scene. The sky writes to the depth buffer, and everything the custom layer draws afterwards fails the depth test. If you render 3D into the map, don't enable the sky layer.</p>
<h3 id="heading-the-idle-event-never-fired-in-a-background-tab">The <code>idle</code> Event Never Fired in a Background Tab</h3>
<p>I preloaded models on <code>map.on("idle")</code>. In a background tab the map can go a very long time without becoming idle, and visitors who opened the site in a tab and came back later got an earthquake with no models. The preload moved to the moment the hazard type is selected.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The whole guide reduces to two structures.</p>
<p>On the ground:</p>
<ol>
<li><p>Align a grid to the map's tile pyramid, so every tiled dataset drops in without resampling.</p>
</li>
<li><p>Decode free elevation tiles into that grid.</p>
</li>
<li><p>Register a canvas as a map source over the grid's rectangle, with <code>animate: true</code>.</p>
</li>
<li><p>Run the simulation on the grid once. Animate by writing pixels every frame.</p>
</li>
<li><p>Use <code>source-atop</code> and <code>destination-in</code> to drape textures exactly inside the simulated shape.</p>
</li>
<li><p>Move the camera. The drawing comes along.</p>
</li>
</ol>
<p>With height:</p>
<ol>
<li><p>Pull buildings from the vector tiles the map already loaded. Deduplicate, as they have no IDs.</p>
</li>
<li><p>Draw them all as <code>fill-extrusion</code> with a per-feature height multiplier, through a GeoJSON copy with <code>promoteId</code> so feature state works.</p>
</li>
<li><p>Decide damage from an attenuation relation and a fragility curve, with randomness per building.</p>
</li>
<li><p>Animate collapse by writing the multiplier each frame.</p>
</li>
<li><p>For the buildings near the camera, render <code>three.js</code> into the map's own GL context with <code>renderingMode: "3d"</code>, so the depth buffer is shared.</p>
</li>
<li><p>Turn footprints into oriented boxes, tip them over, snap them into blocks, and throw instanced debris. Emit dust only from events. Shake the container, not the camera.</p>
</li>
</ol>
<p>The idea under all of it is the one I kept relearning: anything that belongs to the world has to be drawn in the world's coordinates. A canvas on top of the map is a sheet of glass. A canvas inside the map is the ground, and a <code>three.js</code> scene inside the map's GL context is the air above it.</p>
<p>Every improvement that made either simulation look real came from moving something out of the first category and into the second.</p>
<p>The other thing I'd tell myself at the start: the map engine and <code>three.js</code> are not competitors. The map is better at ten thousand static buildings than anything you'll write, and <code>three.js</code> is better at ten moving ones than any expression language.</p>
<p>Give each the job it's good at, and spend your effort on the seam between them, which is almost entirely the coordinate transform in Step 12 and the feature-state trick in Step 11.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a60e4e5f99e7bbad25386f1/3ed70355-abc0-4a98-8285-8012ad46aff9.jpg" alt="The finished scenario: a 30-metre tsunami in Odesa seen from above, with brown floodwater covering the coastal districts and a results panel on the left listing people killed, area flooded, inland reach and maximum depth." style="display: block;" width="1440" height="790" loading="lazy">

<p>You can see both scenarios at <a href="https://hazardsim.com/">hazardsim.com</a>. Pick a coastal city and launch a tsunami, or pick any city, set a magnitude, and press the button. The code in this guide is a cleaned-up version of what runs there. Thanks to Tim for breaking it in ways I never would have.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Add Structured Data (JSON-LD) to a Next.js Site and Validate It ]]>
                </title>
                <description>
                    <![CDATA[ Structured data has always mattered to search engines. When a search engine reads your page, it sees HTML: a heading, some paragraphs, a date somewhere, a name somewhere else. Structured data tells it ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nextjs-json-ld-structured-data/</link>
                <guid isPermaLink="false">6acb575a7dfd7348cce66960</guid>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ SEO ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Saar Twito ]]>
                </dc:creator>
                <pubDate>Sun, 11 Oct 2026 09:31:06 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/4e937052-66b6-461f-ae80-53e8395811e8.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Structured data has always mattered to search engines. When a search engine reads your page, it sees HTML: a heading, some paragraphs, a date somewhere, a name somewhere else.</p>
<p>Structured data tells it directly what those pieces are. This page is an article, this is its headline, this person wrote it, and it was published on this date.</p>
<p>For me, search engine optimization isn't a box to tick at the end. I want the products and sites I build to be found, and to be understood correctly when they are.</p>
<p>That's why I add structured data to every page where it makes sense. And I think it's becoming more relevant, not less, as AI systems start answering questions from web content.</p>
<p>In a Next.js app, nothing writes that data for you. You add it yourself, as a small block of JSON in the pages that need it.</p>
<p>In this tutorial, you'll learn what structured data is and how JSON-LD works. Then you'll add it to a Next.js App Router project: a reusable <code>JsonLd</code> component that's safe to use with any data, organization and article data built from the same content the page renders, and a check that validates all of it after every build.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-structured-data-basics-for-developers">Structured Data Basics for Developers</a></p>
<ul>
<li><p><a href="#heading-what-structured-data-and-json-ld-are">What Structured Data and JSON-LD Are</a></p>
</li>
<li><p><a href="#heading-how-a-json-ld-block-is-built">How a JSON-LD Block Is Built</a></p>
</li>
<li><p><a href="#heading-structured-data-json-ld-schemaorg-and-rich-results">Structured Data, JSON-LD, Schema.org and Rich Results</a></p>
</li>
<li><p><a href="#heading-what-structured-data-does-for-search-and-what-it-doesnt">What Structured Data Does for Search (and What It Doesn't)</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-how-to-build-a-safe-jsonld-component">How to Build a Safe JsonLd Component</a></p>
<ul>
<li><p><a href="#heading-why-not-nextscript">Why Not next/script</a></p>
</li>
<li><p><a href="#heading-why-the-escape-matters">Why the Escape Matters</a></p>
</li>
<li><p><a href="#heading-why-one-component">Why One Component</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-how-to-add-organization-and-website-data-to-the-home-page">How to Add Organization and WebSite Data to the Home Page</a></p>
</li>
<li><p><a href="#heading-how-to-add-article-and-breadcrumb-data-to-a-dynamic-route">How to Add Article and Breadcrumb Data to a Dynamic Route</a></p>
</li>
<li><p><a href="#heading-how-to-validate-your-structured-data">How to Validate Your Structured Data</a></p>
<ul>
<li><p><a href="#heading-check-what-actually-lands-in-the-html">Check What Actually Lands in the HTML</a></p>
</li>
<li><p><a href="#heading-use-the-online-validators">Use the Online Validators</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-how-to-validate-json-ld-automatically-after-every-build">How to Validate JSON-LD Automatically After Every Build</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along, you'll need:</p>
<ul>
<li><p>A Next.js app that uses the App Router and TypeScript. The code in this article was tested with Next.js 16.4.0 and React 19.3.</p>
</li>
<li><p>Basic familiarity with Server Components and dynamic routes.</p>
</li>
<li><p>The <code>schema-dts</code> package, which gives you TypeScript types for structured data.</p>
</li>
</ul>
<p>Install <code>schema-dts</code> as a development dependency, since it only provides types:</p>
<pre><code class="language-bash">npm install -D schema-dts
</code></pre>
<p>The examples use a blog. Wherever you see <code>getPost()</code>, use your own data source: a CMS, a database, or Markdown files.</p>
<h2 id="heading-structured-data-basics-for-developers">Structured Data Basics for Developers</h2>
<p>If you've never worked with structured data, this section gives you just enough to understand the code that follows.</p>
<h3 id="heading-what-structured-data-and-json-ld-are">What Structured Data and JSON-LD Are</h3>
<p>Structured data is a machine-readable description of what a page is about. Instead of leaving a search engine to work out that "Jane Doe" is the author and "2026-09-01" is the publication date, you state it in a format a program can read without guessing.</p>
<p>The words you use come from <a href="https://schema.org/">Schema.org</a>, a shared vocabulary of types (like <code>Article</code>, <code>Person</code> and <code>Organization</code>) and their properties (like <code>headline</code>, <code>author</code> and <code>datePublished</code>). It was started by Google, Microsoft, Yahoo and Yandex, and it's the vocabulary search engines expect.</p>
<p>JSON-LD (JavaScript Object Notation for Linked Data) is one way to write that data. It's a <a href="https://www.w3.org/TR/json-ld11/">W3C standard</a>, and on a web page it lives in a script tag with its own type:</p>
<pre><code class="language-html">&lt;script type="application/ld+json"&gt;
  { "@context": "https://schema.org", "@type": "Article", "headline": "..." }
&lt;/script&gt;
</code></pre>
<p>The browser doesn't run this script. A type that isn't JavaScript turns the tag into what the <a href="https://html.spec.whatwg.org/multipage/scripting.html#data-block">HTML standard</a> calls a data block, "not processed by the user agent, but instead by author script or other tools."</p>
<p>There are two other formats, Microdata and RDFa, which add attributes to your existing HTML elements. Google supports all three, but it <a href="https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data">recommends JSON-LD</a> "if your site's setup allows it." For a React developer, JSON-LD is also the natural fit: it's a plain object you build from data, separate from the JSX that renders the page.</p>
<h3 id="heading-how-a-json-ld-block-is-built">How a JSON-LD Block Is Built</h3>
<p>Here's a JSON-LD block for a blog post:</p>
<pre><code class="language-json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "How Caching Works in Next.js",
  "datePublished": "2026-09-01T09:00:00.000Z",
  "author": {
    "@type": "Person",
    "name": "Jane Doe"
  },
  "publisher": {
    "@type": "Organization",
    "@id": "https://example.com/#organization",
    "name": "Example Dev Blog"
  }
}
</code></pre>
<p>The keys that start with <code>@</code> are JSON-LD keywords. The rest are Schema.org properties:</p>
<ul>
<li><p><code>@context</code> says which vocabulary the names come from. For Schema.org, it's <code>https://schema.org</code>.</p>
</li>
<li><p><code>@type</code> says what kind of thing this is. <code>BlogPosting</code> is a more specific kind of Schema.org <code>Article</code>.</p>
</li>
<li><p><code>headline</code>, <code>datePublished</code> and <code>author</code> are properties of that type. A property can hold text, a date, a URL, or another typed object, like the <code>Person</code> in <code>author</code>.</p>
</li>
<li><p><code>@id</code> gives a thing a unique name, usually a URL with a <code>#</code> fragment. Here, it marks the publisher as the same organization that another block, on the home page, describes with the same <code>@id</code>.</p>
</li>
</ul>
<p>You'll use all four in the code that follows.</p>
<h3 id="heading-structured-data-json-ld-schemaorg-and-rich-results">Structured Data, JSON-LD, Schema.org, and Rich Results</h3>
<p>These four terms get mixed up a lot, so here's how they relate:</p>
<table>
<thead>
<tr>
<th>Term</th>
<th>What it is</th>
</tr>
</thead>
<tbody><tr>
<td>Structured data</td>
<td>The idea: a machine-readable description of a page</td>
</tr>
<tr>
<td>Schema.org</td>
<td>The vocabulary: the types and properties you can use</td>
</tr>
<tr>
<td>JSON-LD</td>
<td>The format: how you write that description into the page</td>
</tr>
<tr>
<td>Rich results</td>
<td>A Google Search feature: enhanced results, like a breadcrumb trail or a product's price and rating, that structured data can make a page eligible for</td>
</tr>
</tbody></table>
<p>In short, you write structured data in JSON-LD, using the Schema.org vocabulary, and Google may use it to show a rich result.</p>
<h3 id="heading-what-structured-data-does-for-search-and-what-it-doesnt">What Structured Data Does for Search (and What It Doesn't)</h3>
<p>Google <a href="https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data">says</a> it uses structured data "to understand the content of the page," and to gather information about the people, books, and companies the markup describes. It also uses it to decide whether a page is eligible for rich results.</p>
<p>Eligible is the important word. Valid JSON-LD doesn't guarantee a rich result, for four reasons:</p>
<ol>
<li><p>Each rich result has its own required properties, listed in Google's documentation for that feature. Markup can be valid Schema.org and still miss them.</p>
</li>
<li><p>Google decides whether to show the feature. Its <a href="https://developers.google.com/search/docs/appearance/structured-data/sd-policies">structured data guidelines</a> say: "Google does not guarantee that your structured data will show up in search results, even if your page is marked up correctly."</p>
</li>
<li><p>The markup has to describe content that's visible on the page. The same guidelines say: "Don't mark up content that is not visible to readers of the page."</p>
</li>
<li><p>Some types no longer produce a rich result at all. Google stopped showing FAQ rich results on May 7, 2026, and How-to rich results in 2023.</p>
</li>
</ol>
<p>Structured data isn't a ranking boost, either. As Google's John Mueller <a href="https://bsky.app/profile/johnmu.com/post/3lmoenzsfwc2c">put it in 2025</a>: "Structured data won't make your site rank better."</p>
<p>What about AI search? Google says there's "no special schema.org structured data that you need to add" to appear in its <a href="https://developers.google.com/search/docs/appearance/ai-features">AI features</a>. Bing's <a href="https://www.bing.com/webmasters/help/webmaster-guidelines-30fba23a">webmaster guidelines</a> say structured data "may support clearer grounding but does not guarantee visibility." OpenAI, Anthropic, and Perplexity don't document using it: their crawler documentation covers crawler access, not markup.</p>
<p>There's a lot of hype around AI search right now, and some of it is justified. But my reasoning doesn't depend on any one company's promise.</p>
<p>I want my content to be as understandable as possible to every system that reads it, whether that's a search engine or an AI tool. Structured data is a clear, accurate description of a page, and that's worth having whoever reads it. Just don't treat it as a trick for getting into AI answers.</p>
<p>How common is it in practice? In the <a href="https://www.greadme.com/blog/seo/greadme-state-of-websites-report-2026">State of Websites 2026 report</a> from Greadme (the website audit tool I build), 63% of 387 audited homepages had structured data. Most of it was well formed: 91% of those sites passed validation with no errors.</p>
<p>But 16% of them still declared <code>FAQPage</code>, a type whose rich result Google had limited to government and health sites in 2023 and has since retired. Valid isn't the same as useful.</p>
<h2 id="heading-how-to-build-a-safe-jsonld-component">How to Build a Safe JsonLd Component</h2>
<p>The Next.js <a href="https://nextjs.org/docs/app/guides/json-ld">JSON-LD guide</a> recommends rendering structured data "as a <code>&lt;script&gt;</code> tag in your <code>layout.js</code> or <code>page.js</code> components." You could paste that tag into every page that needs it. A small component is better, because it keeps the escaping and the types in one place.</p>
<p>Create <code>components/JsonLd.tsx</code>:</p>
<pre><code class="language-tsx">import type { Graph, Thing, WithContext } from "schema-dts";

type JsonLdData = WithContext&lt;Thing&gt; | Graph;

export function serializeJsonLd(data: JsonLdData): string {
  return JSON.stringify(data).replace(/&lt;/g, "\\u003c");
}

export function JsonLd({ data }: { data: JsonLdData }) {
  return (
    &lt;script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: serializeJsonLd(data) }}
    /&gt;
  );
}
</code></pre>
<p>Here's what each part does:</p>
<ul>
<li><p><code>JsonLdData</code> comes from <code>schema-dts</code>. <code>WithContext&lt;Thing&gt;</code> accepts any single Schema.org type with its <code>@context</code>, and <code>Graph</code> accepts a block that holds several. You'll use both.</p>
</li>
<li><p><code>serializeJsonLd</code> turns the object into a string and replaces every <code>&lt;</code> with <code>\u003c</code>. The sections below explain why.</p>
</li>
<li><p><code>dangerouslySetInnerHTML</code> writes that string into the tag exactly as it is. The name sounds alarming, but you control the string, and the escape is what makes it safe to include data from anywhere.</p>
</li>
</ul>
<p>The component has no <code>"use client"</code> directive, so it's a Server Component, and the tag is part of the HTML the server sends.</p>
<h3 id="heading-why-not-nextscript">Why Not next/script</h3>
<p>Next.js has a <code>Script</code> component, and some tutorials use it for JSON-LD. Don't. The JSON-LD guide explains that <code>next/script</code> "is optimized for loading and executing JavaScript," while JSON-LD is data.</p>
<p>The bigger problem shows up in the HTML. With the default <code>afterInteractive</code> strategy, <code>Script</code> content is <a href="https://nextjs.org/docs/app/api-reference/components/script#afterinteractive">"injected into the HTML client-side"</a>. I built a page that renders a <code>Product</code> block through <code>Script</code> and checked the HTML that <code>next build</code> produced.</p>
<p>There was no <code>application/ld+json</code> tag in it. The data existed only inside the JavaScript payload that React reads in the browser.</p>
<p>Google can still find it, because it <a href="https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data">reads JSON-LD</a> that JavaScript injects into the page. But any tool that reads only the HTML sees nothing. A plain <code>&lt;script&gt;</code> puts the data in the HTML for everyone.</p>
<h3 id="heading-why-the-escape-matters">Why the Escape Matters</h3>
<p>Here's the short version: <code>JSON.stringify</code> gives you valid JSON, but not JSON that's safe to put inside HTML. The browser doesn't know your script contains JSON. It looks for the text <code>&lt;/script&gt;</code> to find where the tag ends, and it stops there, even in the middle of a JSON string.</p>
<p>Say a product name comes from a CMS, and someone saves this as the name:</p>
<pre><code class="language-text">Blue Mug &lt;/script&gt;&lt;script&gt;alert(document.cookie)&lt;/script&gt;
</code></pre>
<p>With plain <code>JSON.stringify</code>, the server sends this:</p>
<pre><code class="language-html">&lt;script type="application/ld+json"&gt;{"@context":"https://schema.org","@type":"Product","name":"Blue Mug &lt;/script&gt;&lt;script&gt;alert(document.cookie)&lt;/script&gt;"}&lt;/script&gt;
</code></pre>
<p>The browser ends the JSON-LD tag at the first <code>&lt;/script&gt;</code>. Then it finds a second, ordinary script tag and runs it. That's a cross-site scripting (XSS) attack, and your structured data is now broken JSON as well.</p>
<p>I ran that page through jsdom, which parses HTML the way the HTML standard specifies. The <code>alert</code> ran once, and <code>JSON.parse</code> on the JSON-LD failed with "Unterminated string in JSON."</p>
<p>With the escape, the same value becomes:</p>
<pre><code class="language-html">&lt;script type="application/ld+json"&gt;{"@context":"https://schema.org","@type":"Product","name":"Blue Mug \u003c/script&gt;\u003cscript&gt;alert(document.cookie)\u003c/script&gt;"}&lt;/script&gt;
</code></pre>
<p>There's no <code>&lt;/script&gt;</code> left for the browser to find. <code>\u003c</code> is JSON's own escape for <code>&lt;</code>, so any JSON parser reads it back as the original character. In the same test, nothing ran, and <code>JSON.parse</code> returned the exact name the CMS stored.</p>
<p>You don't need an attacker for this to break a page. The <a href="https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements">HTML standard</a> also lists <code>&lt;!--</code> and <code>&lt;script</code> as sequences that confuse the parser inside a script tag.</p>
<p>In my test, a value containing <code>&lt;!--&lt;script&gt;</code> made the unescaped tag swallow the rest of the page, and the heading after it disappeared from the DOM. With the escape, the page rendered normally.</p>
<p>That's why the Next.js guide recommends replacing <code>&lt;</code> with <code>\u003c</code>. The guide itself only added that advice <a href="https://github.com/vercel/next.js/pull/79627">in May 2025</a>, and many tutorials still use plain <code>JSON.stringify</code>. If your JSON-LD includes anything you didn't type yourself, like titles, descriptions, product names, or reviews, escape it.</p>
<h3 id="heading-why-one-component">Why One Component</h3>
<p>I usually build a component when I notice several places doing the same thing. I want one central place that owns that behavior, so a change or a fix happens once instead of in every copy.</p>
<p>JSON-LD is a good example, because the escape is one line and easy to forget. In a production codebase I maintain, structured data was rendered in nine places.</p>
<p>Seven of them escaped <code>&lt;</code>. Two didn't, and one of those was the component that rendered the structured data for every blog article.</p>
<p>Nothing broke. The article descriptions it handled contain tags like <code>&lt;body&gt;</code> and <code>&lt;video&gt;</code>, which can't end a script tag, and none of them contained <code>&lt;/script</code> or <code>&lt;!--</code>.</p>
<p>But that was luck, not a decision. Whether a page was protected depended on which file you opened.</p>
<p>Moving every block into one <code>JsonLd</code> component fixed that for good. The escape, the choice of a plain <code>&lt;script&gt;</code> over <code>next/script</code>, and the types now live in one place. Every call site gets type checking from the prop type, and <code>serializeJsonLd</code> can be tested on its own.</p>
<h2 id="heading-how-to-add-organization-and-website-data-to-the-home-page">How to Add Organization and WebSite Data to the Home Page</h2>
<p>Start with the data that describes your site as a whole: the organization behind it and the website itself. Google <a href="https://developers.google.com/search/docs/appearance/structured-data/organization">recommends</a> placing organization data "on your home page, or a single page that describes your organization," and adds: "You don't need to include it on every page of your site."</p>
<p>The examples below use two constants for the site's name and address. Put them wherever you keep your configuration:</p>
<pre><code class="language-ts">// lib/site.ts
export const SITE_URL = "https://example.com";
export const SITE_NAME = "Example Dev Blog";
</code></pre>
<p>Then render both types from the home page, <code>app/page.tsx</code>:</p>
<pre><code class="language-tsx">import type { Graph } from "schema-dts";
import { JsonLd } from "@/components/JsonLd";
import { SITE_NAME, SITE_URL } from "@/lib/site";

const siteJsonLd: Graph = {
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "Organization",
      "@id": `${SITE_URL}/#organization`,
      name: SITE_NAME,
      url: SITE_URL,
      logo: `${SITE_URL}/logo.png`,
    },
    {
      "@type": "WebSite",
      "@id": `${SITE_URL}/#website`,
      name: SITE_NAME,
      url: SITE_URL,
      publisher: { "@id": `${SITE_URL}/#organization` },
    },
  ],
};

export default function HomePage() {
  return (
    &lt;main&gt;
      &lt;JsonLd data={siteJsonLd} /&gt;
      &lt;h1&gt;{SITE_NAME}&lt;/h1&gt;
      {/* The rest of your home page */}
    &lt;/main&gt;
  );
}
</code></pre>
<p><code>@graph</code> holds several things in one block that share a single <code>@context</code>. That's why this object is typed as <code>Graph</code> instead of <code>WithContext&lt;...&gt;</code>.</p>
<p>Each item has an <code>@id</code>, and the <code>WebSite</code>'s <code>publisher</code> refers to the <code>Organization</code> by that <code>@id</code> instead of repeating it. Inside one block, a reference with only an <code>@id</code> is enough, because the full definition is right next to it.</p>
<p>You might be tempted to put this in the root layout instead, so it appears everywhere. In the App Router, anything you render in a layout is part of every page under it.</p>
<p>That isn't wrong, but it adds the same block to every page, which Google says you don't need. Use a layout for structured data only when the data really describes every page below it.</p>
<h2 id="heading-how-to-add-article-and-breadcrumb-data-to-a-dynamic-route">How to Add Article and Breadcrumb Data to a Dynamic Route</h2>
<p>Article pages are where structured data earns its keep, and where it most often goes stale. The rule that prevents both problems: build the JSON-LD from the same data the page renders, and mark up only what the reader can see.</p>
<p>Here's a complete <code>app/blog/[slug]/page.tsx</code>:</p>
<pre><code class="language-tsx">import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import type { BlogPosting, BreadcrumbList, WithContext } from "schema-dts";
import { JsonLd } from "@/components/JsonLd";
import { getAllPosts, getPost } from "@/lib/posts";
import { SITE_NAME, SITE_URL } from "@/lib/site";

export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((post) =&gt; ({ slug: post.slug }));
}

export default async function PostPage({
  params,
}: {
  params: Promise&lt;{ slug: string }&gt;;
}) {
  const { slug } = await params;
  const post = await getPost(slug);
  if (!post) notFound();

  const breadcrumbs = [
    { name: "Home", path: "/" },
    { name: "Blog", path: "/blog" },
    { name: post.title, path: `/blog/${post.slug}` },
  ];

  const articleJsonLd: WithContext&lt;BlogPosting&gt; = {
    "@context": "https://schema.org",
    "@type": "BlogPosting",
    headline: post.title,
    description: post.description,
    image: post.image,
    datePublished: post.publishedAt,
    dateModified: post.updatedAt,
    author: { "@type": "Person", name: post.author.name, url: post.author.url },
    publisher: {
      "@type": "Organization",
      "@id": `${SITE_URL}/#organization`,
      name: SITE_NAME,
    },
  };

  const breadcrumbJsonLd: WithContext&lt;BreadcrumbList&gt; = {
    "@context": "https://schema.org",
    "@type": "BreadcrumbList",
    itemListElement: breadcrumbs.map((crumb, index) =&gt; ({
      "@type": "ListItem",
      position: index + 1,
      name: crumb.name,
      item: new URL(crumb.path, SITE_URL).href,
    })),
  };

  return (
    &lt;article&gt;
      &lt;JsonLd data={articleJsonLd} /&gt;
      &lt;JsonLd data={breadcrumbJsonLd} /&gt;

      &lt;nav aria-label="Breadcrumb"&gt;
        {breadcrumbs.map((crumb, index) =&gt; (
          &lt;span key={crumb.path}&gt;
            {index &gt; 0 &amp;&amp; " / "}
            &lt;Link href={crumb.path}&gt;{crumb.name}&lt;/Link&gt;
          &lt;/span&gt;
        ))}
      &lt;/nav&gt;

      &lt;h1&gt;{post.title}&lt;/h1&gt;
      &lt;p&gt;
        By &lt;a href={post.author.url}&gt;{post.author.name}&lt;/a&gt; ·{" "}
        &lt;time dateTime={post.publishedAt}&gt;{post.publishedAt.slice(0, 10)}&lt;/time&gt;
      &lt;/p&gt;
      &lt;Image src={post.image} alt="" width={1200} height={675} /&gt;
      &lt;p&gt;{post.description}&lt;/p&gt;
    &lt;/article&gt;
  );
}
</code></pre>
<p><code>next/image</code> only loads remote images from hosts you allow, so add your image host to <a href="https://nextjs.org/docs/app/api-reference/components/image#remotepatterns"><code>images.remotePatterns</code></a> in <code>next.config.ts</code> if it isn't there already.</p>
<p>Every value in <code>articleJsonLd</code> comes from <code>post</code>, the same object the JSX renders. The headline is the <code>&lt;h1&gt;</code>, the author is the byline, and the dates are the date on the page.</p>
<p>If an editor changes the title, both change together. Compare that with a hardcoded <code>dateModified</code> or a copied-in rating, which stay the same while the page moves on.</p>
<p>The breadcrumbs work the same way. One <code>breadcrumbs</code> array produces both the visible navigation and the <code>BreadcrumbList</code>, so the markup can't describe a trail the reader doesn't see. Google <a href="https://developers.google.com/search/docs/appearance/structured-data/breadcrumb">requires</a> a <code>position</code> and a <code>name</code> for each item, an <code>item</code> URL for every item except the last, and at least two items.</p>
<p>Two things matter most to me with structured data. First, it has to be implemented correctly, which is what the validation sections below are for.</p>
<p>Second, it has to match what the reader can actually see. If a piece of information exists only in the JSON-LD and not on the page, it shouldn't be there.</p>
<p>Google's own <a href="https://developers.google.com/search/docs/appearance/structured-data/sd-policies">guidelines</a> say the same, and Bing's say misleading markup "may be ignored." Building the JSON-LD from the rendered data is the simplest way to follow that rule without thinking about it.</p>
<p>The <code>publisher</code> includes a <code>name</code> next to its <code>@id</code>. On the home page, a bare <code>@id</code> was enough, because the full <code>Organization</code> sat in the same block.</p>
<p>Here, it's on a different page, and tools that check one page at a time can't see it. The name keeps this page's data complete on its own, and the shared <code>@id</code> still marks it as the same organization.</p>
<p>Article has no required properties in Google's <a href="https://developers.google.com/search/docs/appearance/structured-data/article">Article documentation</a>. It recommends <code>author</code>, <code>datePublished</code>, <code>dateModified</code>, <code>headline</code> and <code>image</code>, with dates in ISO 8601 format and a time zone. The example above includes all of them.</p>
<p>The <code>schema-dts</code> types catch mistakes while you type. If you misspell a property, TypeScript stops you:</p>
<pre><code class="language-text">Object literal may only specify known properties, but 'headLine' does not exist in type
'BlogPostingLeaf &amp; { "@context": "https://schema.org"; }'. Did you mean to write 'headline'?
</code></pre>
<p>They also catch the wrong <code>@type</code> for the annotation and the wrong kind of value, like a number for <code>datePublished</code>.</p>
<p>What they can't catch is anything that depends on Google's rules or on what's actually on the page. A date string like <code>"last Tuesday"</code> type-checks fine. That's what validation is for.</p>
<h2 id="heading-how-to-validate-your-structured-data">How to Validate Your Structured Data</h2>
<p>Validation happens in two places: the HTML your server actually sends, and the tools that read it the way a search engine does.</p>
<h3 id="heading-check-what-actually-lands-in-the-html">Check What Actually Lands in the HTML</h3>
<p>Start by looking at the real output, not your source code. Build and start the app:</p>
<pre><code class="language-bash">npm run build
npm start
</code></pre>
<p>Then, in another terminal, fetch a page and pull out its JSON-LD:</p>
<pre><code class="language-bash">curl -s http://localhost:3000/blog/nextjs-caching \
  | grep -o '&lt;script type="application/ld+json"&gt;[^&lt;]*&lt;/script&gt;'
</code></pre>
<p>You should see one line per block:</p>
<pre><code class="language-html">&lt;script type="application/ld+json"&gt;{"@context":"https://schema.org","@type":"BlogPosting","headline":"How Caching Works in Next.js","description":"A practical tour of the \u003cLink&gt; prefetch, the data cache and revalidation.","image":"https://example.com/images/nextjs-caching.png","datePublished":"2026-09-01T09:00:00.000Z","dateModified":"2026-09-20T12:00:00.000Z","author":{"@type":"Person","name":"Jane Doe","url":"https://example.com/authors/jane-doe"},"publisher":{"@type":"Organization","@id":"https://example.com/#organization","name":"Example Dev Blog"}}&lt;/script&gt;
&lt;script type="application/ld+json"&gt;{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://example.com/"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://example.com/blog"},{"@type":"ListItem","position":3,"name":"How Caching Works in Next.js","item":"https://example.com/blog/nextjs-caching"}]}&lt;/script&gt;
</code></pre>
<p>The description shows the escape at work. The post's description mentions the <code>&lt;Link&gt;</code> component, and its <code>&lt;</code> arrives as <code>\u003c</code>.</p>
<p>This check also catches the <code>next/script</code> problem from earlier and any JSON-LD added in a <code>useEffect</code>. If the data is only added in the browser, the <code>grep</code> finds nothing. You can do the same check with your browser's View Source, but not with the developer tools' Elements panel, which shows the page after JavaScript has run.</p>
<p>You might also notice that <code>application/ld+json</code> appears more often in the full response than there are tags. Next.js sends the rendered React tree a second time as the React Server Components payload, the data React uses to hydrate the page, and your JSON-LD string is part of that tree.</p>
<p>So every byte of structured data ships twice. That's a good reason to keep JSON-LD to the properties you need, and not to copy a whole article body into it.</p>
<h3 id="heading-use-the-online-validators">Use the Online Validators</h3>
<p>Two free tools check structured data from a search engine's point of view, and each answers a different question.</p>
<p>The <a href="https://search.google.com/test/rich-results">Rich Results Test</a> is Google's tool. It <a href="https://support.google.com/webmasters/answer/7445569">shows</a> which Google rich result types it found on a page, along with any errors or suggestions.</p>
<p>It works best with a URL. A preview deployment works well for that, and Google <a href="https://developers.google.com/search/docs/appearance/structured-data/generate-structured-data-with-javascript">recommends</a> the URL input over the code input "because there are JavaScript limitations when using the code input." For a local build, paste the HTML from <code>curl</code> into its code tab.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66c44f7dd6285e754adb356c/ca103ea7-13f7-4c4a-be8a-11a1e0a08de2.png" alt="Google's Rich Results Test showing 2 valid items detected for the example blog post: Articles and Breadcrumbs, with 1 valid item each" style="display: block;" width="1298" height="832" loading="lazy">

<p>The <a href="https://validator.schema.org/">Schema Markup Validator</a> checks your markup against the Schema.org vocabulary itself. Google's <a href="https://developers.google.com/search/blog/2020/12/structured-data-testing-tool-update">announcement</a> of the tool describes its purpose as checking "syntax and compliance of markup with schema.org standards," without checking Google's rich result types. Use it for types Google doesn't use for rich results, or when you want to know that the markup is valid Schema.org regardless of any search engine.</p>
<img src="https://cdn.hashnode.com/uploads/covers/66c44f7dd6285e754adb356c/a5bcea2b-f6be-4656-b52a-b844a769a683.png" alt="The Schema Markup Validator showing 0 errors and 0 warnings for the example blog post, with BreadcrumbList and BlogPosting detected" style="display: block;" width="1280" height="860" loading="lazy">

<p>After you deploy, Google Search Console takes over. Its rich result reports show valid items and errors across every page Google has crawled, and the URL Inspection tool shows what Google saw on a single page. Google's <a href="https://developers.google.com/search/docs/appearance/structured-data/intro-structured-data">own advice</a> is to use the Rich Results Test "during development, and the Rich result status reports after deployment."</p>
<h2 id="heading-how-to-validate-json-ld-automatically-after-every-build">How to Validate JSON-LD Automatically After Every Build</h2>
<p>Structured data has a lot of types, properties and rules, and it's easy to make a mistake in the syntax or the implementation. You already deal with that kind of risk everywhere else in software development: you check types, run linters, and write tests, so problems show up before users see them. Structured data shouldn't be any different.</p>
<p>The online tools are great for a first check, but nobody pastes every URL into them after every change. Structured data usually breaks later, quietly: someone renames a field in the CMS, a refactor drops a property, or a heading changes and the JSON-LD doesn't. A small script that runs after every build catches those regressions before they ship.</p>
<p>This one fetches your pages from the running app and checks four things:</p>
<ol>
<li><p>Every JSON-LD block is valid JSON.</p>
</li>
<li><p><code>@context</code> is <code>https://schema.org</code>.</p>
</li>
<li><p>Each type has the properties your site promises, including Google's required breadcrumb fields.</p>
</li>
<li><p>The <code>BlogPosting</code> headline matches the page's <code>&lt;h1&gt;</code>, the visible-content rule as a check.</p>
</li>
</ol>
<p>Create <code>scripts/check-jsonld.mjs</code>:</p>
<pre><code class="language-js">// Checks the JSON-LD on a running Next.js server: npm run build &amp;&amp; npm start, then run this.
const BASE_URL = process.env.BASE_URL ?? "http://localhost:3000";

// Pages that should carry structured data.
const PAGES = ["/", "/blog/nextjs-caching"];

// The properties this site promises for each type.
const REQUIRED = {
  Organization: ["name", "url", "logo"],
  WebSite: ["name", "url"],
  BlogPosting: ["headline", "datePublished", "author", "image"],
  BreadcrumbList: ["itemListElement"],
};

const errors = [];

function fail(page, message) {
  errors.push(page + ": " + message);
}

function decodeEntities(text) {
  return text
    .replace(/&amp;lt;/g, "&lt;")
    .replace(/&amp;gt;/g, "&gt;")
    .replace(/&amp;quot;/g, '"')
    .replace(/&amp;#x27;|&amp;#39;/g, "'")
    .replace(/&amp;amp;/g, "&amp;");
}

function checkBreadcrumbs(node, page) {
  const items = node.itemListElement ?? [];
  if (items.length &lt; 2) {
    fail(page, "BreadcrumbList needs at least two items");
  }
  items.forEach((item, index) =&gt; {
    const isLast = index === items.length - 1;
    if (item.position !== index + 1 || !item.name || (!isLast &amp;&amp; !item.item)) {
      fail(page, `breadcrumb ${index + 1} needs position, name and item`);
    }
  });
}

for (const page of PAGES) {
  const html = await (await fetch(BASE_URL + page)).text();

  // Safe to match with a regex because the JsonLd component escapes every "&lt;".
  const blocks = [
    ...html.matchAll(/&lt;script type="application\/ld\+json"&gt;(.*?)&lt;\/script&gt;/gs),
  ].map((match) =&gt; match[1]);

  if (blocks.length === 0) {
    fail(page, "no JSON-LD found");
    continue;
  }

  const h1 = html.match(/&lt;h1[^&gt;]*&gt;(.*?)&lt;\/h1&gt;/s)?.[1].replace(/&lt;[^&gt;]+&gt;/g, "");

  for (const block of blocks) {
    let data;
    try {
      data = JSON.parse(block);
    } catch (error) {
      fail(page, `invalid JSON (${error.message})`);
      continue;
    }

    if (data["@context"] !== "https://schema.org") {
      fail(page, '@context should be "https://schema.org"');
    }

    for (const node of data["@graph"] ?? [data]) {
      const type = node["@type"];
      for (const property of REQUIRED[type] ?? []) {
        if (node[property] === undefined) {
          fail(page, type + ' is missing "' + property + '"');
        }
      }
      if (type === "BreadcrumbList") checkBreadcrumbs(node, page);
      if (
        type === "BlogPosting" &amp;&amp;
        node.headline !== decodeEntities(h1 ?? "")
      ) {
        fail(page, `headline "${node.headline}" doesn't match the &lt;h1&gt;`);
      }
    }
  }
}

if (errors.length &gt; 0) {
  console.error(errors.join("\n"));
  process.exit(1);
}
console.log(`JSON-LD OK on ${PAGES.length} pages`);
</code></pre>
<p>A few details are worth pointing out:</p>
<ul>
<li><p><code>REQUIRED</code> is your own contract, not Google's. Google lists no required properties for Article, so the list says what this site promises to include. Add a type to it when you start using one.</p>
</li>
<li><p>The regex that finds the blocks is reliable here only because the <code>JsonLd</code> component escapes every <code>&lt;</code>. No value can contain <code>&lt;/script&gt;</code>, so the first <code>&lt;/script&gt;</code> always ends the block. The escape protects your tests as well as your users.</p>
</li>
<li><p>React escapes characters like <code>'</code> and <code>&amp;</code> in the <code>&lt;h1&gt;</code>, so <code>decodeEntities</code> turns them back before the headline comparison.</p>
</li>
</ul>
<p>The script uses the built-in <code>fetch</code>, so it needs no dependencies. Add it to <code>package.json</code>:</p>
<pre><code class="language-json">{
  "scripts": {
    "check:jsonld": "node scripts/check-jsonld.mjs"
  }
}
</code></pre>
<p>With <code>npm start</code> running, run it in a second terminal:</p>
<pre><code class="language-bash">npm run check:jsonld
</code></pre>
<p>When everything is in order, it prints <code>JSON-LD OK on 2 pages</code>. To see it fail, I removed the organization's <code>logo</code>, changed the post's <code>&lt;h1&gt;</code> without changing its data, and added the unescaped page from earlier to the list. The script reported all three and exited with code 1:</p>
<pre><code class="language-text">/: Organization is missing "logo"
/blog/nextjs-caching: headline "How Caching Works in Next.js" doesn't match the &lt;h1&gt;
/experiments/unescaped: invalid JSON (Unterminated string in JSON at position 68 (line 1 column 69))
</code></pre>
<p>In CI, run it after <code>npm run build</code>, with <code>npm start</code> running in the background, and set <code>BASE_URL</code> if the server isn't on port 3000. The non-zero exit code fails the job, so broken structured data never reaches production.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Structured data describes your pages to search engines in a form they don't have to guess at. In this tutorial, you added it to a Next.js App Router site:</p>
<ul>
<li><p>A <code>JsonLd</code> component that renders a plain <code>&lt;script&gt;</code> and escapes <code>&lt;</code>, so no value can break out of the tag</p>
</li>
<li><p>Organization and website data on the home page, linked with <code>@id</code></p>
</li>
<li><p>Article and breadcrumb data built from the same data the page renders</p>
</li>
<li><p>Checks for what lands in the HTML, the online validators, and a script that validates your JSON-LD after every build</p>
</li>
</ul>
<p>I'd call structured data almost essential today. It's also never been easier to write: an AI assistant can generate a JSON-LD block for any page in seconds. But generated isn't the same as correct.</p>
<p>Check that what it wrote is valid, that it includes the properties Google asks for, and that every value matches what's actually on your page. That's what the validators and the check script are for.</p>
<p>And remember that valid markup makes a page eligible for rich results, not guaranteed to get them.</p>
<p>If you want a second opinion on a live page, the free <a href="https://www.greadme.com/schema-validator">Greadme Schema Validator</a> checks any URL against Schema.org and Google's rich result requirements, with no sign-up needed.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How AI Is Changing Email Deliverability: A Technical Guide to Sender Reputation and Inbox Placement  ]]>
                </title>
                <description>
                    <![CDATA[ Sending an email doesn't always mean it will reach the recipient's inbox. Sometimes, an email is sent successfully by an application but ends up in the spam folder instead. This can be a real problem  ]]>
                </description>
                <link>https://www.freecodecamp.org/news/ai-email-deliverability-explained/</link>
                <guid isPermaLink="false">6ac38287d6fd64daae93bf3c</guid>
                
                    <category>
                        <![CDATA[ Artificial Intelligence ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Machine Learning ]]>
                    </category>
                
                    <category>
                        <![CDATA[ email ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Programming Blogs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Reetain Raina ]]>
                </dc:creator>
                <pubDate>Mon, 05 Oct 2026 10:57:11 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/ccac1a88-7bba-4136-a680-f20637c173b1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Sending an email doesn't always mean it will reach the recipient's inbox. Sometimes, an email is sent successfully by an application but ends up in the spam folder instead.</p>
<p>This can be a real problem for developers, especially when they're sending important messages such as password-reset links, account verification codes, or payment confirmations.</p>
<p>This is where email deliverability comes into the picture. Email providers don't just check whether an email has been sent. They also examine who sent it, how it was sent, and whether it looks trustworthy.</p>
<p>To do this, providers use techniques such as sender reputation, email authentication, and AI-powered spam filters. As AI becomes more involved in this process, understanding how these systems work is becoming increasingly important for developers.</p>
<h3 id="heading-what-well-cover-here">What We'll Cover Here:</h3>
<ul>
<li><p><a href="#heading-how-email-providers-traditionally-evaluated-sender-reputation">How Email Providers Traditionally Evaluated Sender Reputation</a></p>
<ul>
<li><p><a href="#heading-what-is-sender-reputation">What Is Sender Reputation?</a></p>
</li>
<li><p><a href="#heading-the-signals-behind-traditional-email-filtering">The Signals Behind Traditional Email Filtering</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-how-ai-is-changing-the-way-email-providers-detect-spam">How AI Is Changing the Way Email Providers Detect Spam</a></p>
<ul>
<li><p><a href="#heading-from-fixed-rules-to-machine-learning">From Fixed Rules to Machine Learning</a></p>
</li>
<li><p><a href="#heading-how-ai-recognises-suspicious-email-behaviour">How AI Recognises Suspicious Email Behaviour</a></p>
</li>
<li><p><a href="#heading-why-context-matters-more-than-individual-keywords">Why Context Matters More Than Individual Keywords</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-sender-reputation-in-the-age-of-ai-what-has-actually-changed">Sender Reputation in the Age of AI: What Has Actually Changed?</a></p>
<ul>
<li><p><a href="#heading-why-good-authentication-doesnt-guarantee-inbox-placement">Why Good Authentication Doesn't Guarantee Inbox Placement</a></p>
</li>
<li><p><a href="#heading-why-reputation-can-change-over-time">Why Reputation Can Change Over Time</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-inbox-placement-why-the-same-email-can-have-different-outcomes">Inbox Placement: Why the Same Email Can Have Different Outcomes</a></p>
</li>
<li><p><a href="#heading-what-developers-can-do-to-improve-email-deliverability">What Developers Can Do to Improve Email Deliverability</a></p>
<ul>
<li><p><a href="#heading-configure-spf-dkim-and-dmarc-correctly">Configure SPF, DKIM and DMARC Correctly</a></p>
</li>
<li><p><a href="#heading-monitor-bounces-and-spam-complaints">Monitor Bounces and Spam Complaints</a></p>
</li>
<li><p><a href="#heading-maintain-consistent-sending-patterns">Maintain Consistent Sending Patterns</a></p>
</li>
<li><p><a href="#heading-test-inbox-placement-across-providers">Test Inbox Placement Across Providers</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-the-limitations-of-ai-powered-email-filtering">The Limitations of AI-Powered Email Filtering</a></p>
</li>
<li><p><a href="#heading-wrap-up">Wrap Up</a></p>
</li>
</ul>
<h2 id="heading-how-email-providers-traditionally-evaluated-sender-reputation">How Email Providers Traditionally Evaluated Sender Reputation</h2>
<p>Before exploring how modern filtering works, we should look at the established systems that still form the foundation of email sorting.</p>
<h3 id="heading-what-is-sender-reputation">What Is Sender Reputation?</h3>
<p>At the core of these systems lies sender reputation, which is an ongoing assessment of a sender's trustworthiness. This trust score is calculated based on historical sending behaviour, cryptographic authentication, and how previous recipients have responded to your messages.</p>
<h3 id="heading-the-signals-behind-traditional-email-filtering">The Signals Behind Traditional Email Filtering</h3>
<p>To build this reputation, traditional spam filtering relies on several specific, measurable signals.</p>
<p>First, IP reputation tracks the historical behaviour specifically associated with your server's IP address. Alongside this, domain reputation evaluates the historical trust tied to the domain name used in your sender address. These identifiers are then cross-referenced with bounce rates, as repeatedly sending messages to invalid addresses strongly indicates poor list hygiene.</p>
<p>Spam complaints can also hurt sender reputation when recipients repeatedly mark messages as spam.</p>
<p>Email authentication is another important part of the process. Three protocols are commonly used here:</p>
<ol>
<li><p><strong>SPF (Sender Policy Framework)</strong> tells receiving servers which servers are allowed to send email for a domain.</p>
</li>
<li><p><strong>DKIM (DomainKeys Identified Mail)</strong> adds a digital signature to outgoing messages, allowing the receiving server to verify that the message was authorised and wasn't changed in transit.</p>
</li>
<li><p><strong>DMARC (Domain-based Message Authentication, Reporting and Conformance)</strong> builds on SPF and DKIM by allowing domain owners to specify how receiving servers should handle messages that fail authentication and by providing reports about those failures.</p>
</li>
</ol>
<p>Because these signals are so reliable, traditional filtering has effectively utilized rules and statistical techniques for years. AI isn't replacing every existing mechanism here. These foundational signals absolutely still matter, but modern email providers can now evaluate much more than just a sender's technical configuration.</p>
<h2 id="heading-how-ai-is-changing-the-way-email-providers-detect-spam">How AI Is Changing the Way Email Providers Detect Spam</h2>
<p>Building upon those traditional signals, artificial intelligence introduces an entirely new layer of contextual analysis.</p>
<h3 id="heading-from-fixed-rules-to-machine-learning">From Fixed Rules to Machine Learning</h3>
<p>Historically, rule-based systems flagged messages using predefined conditions, such as known malicious signatures or universally suspicious links.</p>
<p>Machine learning models, on the other hand, dynamically learn evolving patterns from massive collections of labeled messages. This shift allows providers to adapt to new threats instantly without waiting for manual rule updates.</p>
<h3 id="heading-how-ai-recognises-suspicious-email-behaviour">How AI Recognises Suspicious Email Behaviour</h3>
<p>By leveraging this dynamic learning, machine learning systems evaluate multiple signals simultaneously rather than checking them sequentially. These comprehensive models analyze message content, looking closely at suspicious wording alongside structural anomalies. Simultaneously, they scrutinize the characteristics of all embedded links, attachments, and the domains hosting them.</p>
<p>This deep inspection is paired with an analysis of sending frequency, where any sudden spikes in volume immediately trigger closer inspection. The AI cross-references this activity with your historical sender behaviour and incorporates real-time recipient interactions to create a holistic profile of the email's intent.</p>
<h3 id="heading-why-context-matters-more-than-individual-keywords">Why Context Matters More Than Individual Keywords</h3>
<p>Because these systems evaluate data holistically, context matters far more than individual keywords. Consider two separate emails containing the word "free." One could be a legitimate account notification from a developer community, while the other might combine deceptive links with erratic sending patterns.</p>
<p>Modern filtering evaluates these characteristics collectively, meaning spam detection is no longer about simply identifying a single suspicious word. Instead, it focuses on recognizing suspicious patterns across text, senders and historical behaviour.</p>
<p>In fact, <a href="https://www.pcmag.com/news/google-upgrades-gmails-spam-filter-with-new-retvec-system">recent upgrades to Google's spam filters include RETVec (Resilient &amp; Efficient Text Vectorizer)</a>, an AI model that vectorizes text to capture the underlying meaning of words. This technology allows Gmail to effectively detect manipulative text patterns, like spaced-out characters or homoglyphs, while significantly reducing false positives.</p>
<h2 id="heading-sender-reputation-in-the-age-of-ai-what-has-actually-changed">Sender Reputation in the Age of AI: What Has Actually Changed?</h2>
<p>With this advanced contextual analysis in play, the concept of sender reputation has fundamentally evolved.</p>
<p>Reputation is no longer simply a permanent, static score assigned to an email address. Instead, it's a fluid evaluation where your sending patterns, authentication failures, and recipient responses continuously influence how your traffic is filtered.</p>
<p>Because AI systems monitor these trends in real-time, sudden increases in sending volume will almost always trigger additional, aggressive scrutiny. Machine learning excels at identifying this type of unusual behaviour, which would be incredibly difficult to reliably detect using simple, static rules.</p>
<h3 id="heading-why-good-authentication-doesnt-guarantee-inbox-placement">Why Good Authentication Doesn't Guarantee Inbox Placement</h3>
<p>While establishing a solid technical foundation is necessary, it's no longer sufficient on its own. <strong>SPF</strong>, <strong>DKIM</strong> and <strong>DMARC</strong> establish important cryptographic proof of your email's authenticity, but authentication alone doesn't prove that a message is actually wanted or trustworthy.</p>
<h3 id="heading-why-reputation-can-change-over-time">Why Reputation Can Change Over Time</h3>
<p>This dynamic nature explains why reputation can fluctuate dramatically over time. If a previously reliable domain suddenly starts dispatching massive volumes of unsolicited messages, its stellar historical reputation won't protect the new, anomalous traffic from immediate AI intervention.</p>
<p>Each provider maintains its own independent filtering infrastructure, meaning there's no single, universal AI-generated reputation score governing the entire internet.</p>
<h2 id="heading-inbox-placement-why-the-same-email-can-have-different-outcomes">Inbox Placement: Why the Same Email Can Have Different Outcomes</h2>
<p>Because these filtering architectures are decentralized, the exact same email can experience vastly different outcomes depending on where it lands.</p>
<p>Providers like <strong>Gmail</strong>, <strong>Outlook</strong>, and <strong>Yahoo</strong> all operate entirely independent filtering infrastructures with unique internal policies. Consequently, an authenticated message might easily reach the primary inbox of one recipient while being silently routed to the spam folder of another.</p>
<p>This discrepancy happens because each provider places a different weighted value on your domain reputation, sending history, and specific user engagement signals.</p>
<p>For example, if I send an identical newsletter to both Gmail and Outlook users, the message will pass the same <strong>DNS authentication</strong> checks everywhere. But their respective <strong>AI systems</strong> evaluate the content, sender history, and internal user metrics differently, leading to distinct inbox placement results. Therefore, inbox placement can never be absolutely guaranteed by any single authentication setting.</p>
<h2 id="heading-what-developers-can-do-to-improve-email-deliverability">What Developers Can Do to Improve Email Deliverability</h2>
<p>Knowing that these systems are complex and fragmented, developers must take proactive steps to align their infrastructure with AI expectations.</p>
<h3 id="heading-configure-spf-dkim-and-dmarc-correctly">Configure SPF, DKIM and DMARC Correctly</h3>
<p>The first step is to configure your email authentication records correctly. For example, an SPF record is published as a DNS TXT record and identifies which servers are authorised to send email for your domain. A simplified example might look like this:</p>
<p><code>v=spf1 include:_spf.example.com</code> <code>~all</code></p>
<p>The exact value depends on the email service you use, so you should use the SPF record provided by your email provider rather than copying this example directly.</p>
<p>DKIM works differently. Your email provider generates a cryptographic key pair. The public key is published in your domain's DNS records, while the private key is used to sign outgoing messages. Receiving servers can then use the public key to verify the signature.</p>
<p>DMARC connects these mechanisms. A basic monitoring record might look like:</p>
<p><code>v=DMARC1; p=none; rua=mailto:dmarc@example.com</code></p>
<p>Here, <code>p=none</code> tells receiving servers to monitor authentication failures without asking them to reject or quarantine those messages, while <code>rua</code> specifies an address for aggregate reports.</p>
<p>These records are only examples. The correct values depend on your email infrastructure, so always follow the documentation provided by your email service.</p>
<h3 id="heading-monitor-bounces-and-spam-complaints">Monitor Bounces and Spam Complaints</h3>
<p>Beyond authentication, you should monitor how recipients and receiving providers respond to your messages. Hard bounces, spam complaints, and sudden changes in delivery rates can reveal problems with an email list or sending setup.</p>
<p>For Gmail recipients, <a href="https://postmaster.google.com/">Google Postmaster Tools</a> provides eligible senders with information about metrics such as spam rates, authentication and domain or IP reputation. Microsoft provides <a href="https://sendersupport.olc.protection.outlook.com/snds/">SNDS</a> for monitoring IP addresses that send mail to Microsoft's consumer email services. Yahoo also provides sender guidance and resources through its <a href="https://senders.yahooinc.com/">Sender Hub</a>.</p>
<p>These tools don't guarantee inbox placement, but they can help you identify delivery problems instead of relying only on whether your application reports that an email was successfully sent.</p>
<h3 id="heading-maintain-consistent-sending-patterns">Maintain Consistent Sending Patterns</h3>
<p>To avoid sudden changes in sending behaviour, you should keep your email volume relatively consistent and scale it gradually as your application grows. A domain that normally sends a few hundred emails a day, for example, may attract additional scrutiny if it suddenly starts sending thousands without an established sending history.</p>
<p>For a new domain or email account, some senders use a <a href="https://www.warmy.io/product/warm-up-email/">warm-up platform</a> to gradually increase sending activity and build a history of email traffic. But warm-up is only one part of the process. It doesn't replace proper SPF, DKIM, or DMARC configuration, good list hygiene, or responsible sending practices and it can't guarantee inbox placement.</p>
<h3 id="heading-test-inbox-placement-across-providers">Test Inbox Placement Across Providers</h3>
<p>Finally, test important emails across more than one provider. A successful SMTP response only tells you that the receiving server accepted the message. It doesn't guarantee that the message reached the primary inbox.</p>
<p>For example, you could send a test password-reset email to Gmail, Outlook, and Yahoo accounts and check whether the message arrives in the inbox, spam folder, or another filtered location. This can help reveal provider-specific delivery problems.</p>
<p>For ongoing monitoring, tools such as <strong>Google Postmaster Tools</strong>, <strong>Microsoft SNDS,</strong> and <strong>Yahoo Sender Hub</strong> can provide additional information about sender reputation and delivery-related signals.</p>
<h2 id="heading-the-limitations-of-ai-powered-email-filtering">The Limitations of AI-Powered Email Filtering</h2>
<p>Despite these powerful monitoring tools and advanced algorithms, it's important to acknowledge what AI can't do flawlessly.</p>
<p>Machine learning drastically improves pattern recognition, but it doesn't make spam classification infallible. Legitimate emails frequently suffer from false positives, where critical messages are incorrectly classified as junk due to an algorithmic misjudgment.</p>
<p>Spammers also constantly modify their tactics, forcing these models to perpetually adapt to changing behaviour. This constant evolution is compounded by limited transparency, as email providers deliberately don't disclose the exact mathematical weights of their filtering models to prevent abuse.</p>
<p>Also, some filtering capabilities are inherently limited by privacy considerations, as providers must balance message analysis with strict data protection regulations. Consequently, an entirely legitimate password-reset email might still be flagged simply because an underlying model detected a temporary, unexpected variance in your sending volume.</p>
<h2 id="heading-wrap-up">Wrap Up</h2>
<p>While occasional false positives are inevitable, AI has undeniably made email filtering vastly more capable of analyzing complex, nuanced contexts. Still, traditional sender reputation remains crucially important, working hand-in-hand with strict authentication and responsible sending practices.</p>
<p>Developers should internalize the reality that a successful network delivery is entirely different from successful inbox placement. Ultimately, while AI helps email providers decide which messages deserve the user's attention, developers still carry the responsibility of giving those intelligent systems consistently good reasons to trust their infrastructure.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build an AI Support System That Automatically Routes Bugs to GitHub with Next.js and Jev ]]>
                </title>
                <description>
                    <![CDATA[ Every website gets feedback, and most of it ends up somewhere awkward. A visitor finds a broken button and emails you. Someone else leaves a comment on social media about a page that won't load on the ]]>
                </description>
                <link>https://www.freecodecamp.org/news/build-an-ai-support-system-that-automatically-routes-bugs-to-github/</link>
                <guid isPermaLink="false">6abfc515257f8ade20662b79</guid>
                
                    <category>
                        <![CDATA[ AI ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Next.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ GitHub ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ TypeScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Open Source ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Andrew Baisden ]]>
                </dc:creator>
                <pubDate>Fri, 02 Oct 2026 14:52:05 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/13431986-02ba-4353-8fa7-793542e0e03f.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Every website gets feedback, and most of it ends up somewhere awkward. A visitor finds a broken button and emails you. Someone else leaves a comment on social media about a page that won't load on their phone. A third person fills in your contact form with a feature idea, and it sits in your inbox between a newsletter and a receipt.</p>
<p>When you finally sit down to fix things, the bug reports are scattered across three places. Half of them are missing details, and the ones that do make it into GitHub were copied there by hand, sometimes with the visitor's email address still pasted into a public issue.</p>
<p>I wanted something better for my own projects, so I built it. <strong>IssueRelay</strong> gives any React website a small support widget where visitors can ask a question, report a bug, or suggest a feature. Every report is saved to your own database first. Then an AI model called Jev classifies it, a set of plain rules in code decides where it goes, and you review it in a private dashboard.</p>
<p>When you confirm that a report really is a bug, IssueRelay creates one clean GitHub issue for it, with the visitor's private details removed. When you later close that issue on GitHub, the support ticket closes too.</p>
<p>In this tutorial, you'll learn how the whole system works, from the widget in the browser to the webhook that keeps GitHub and the dashboard in sync. You'll also see how to deploy your own copy in about 15 minutes.</p>
<p>IssueRelay is open source on GitHub at <a href="https://github.com/andrewbaisden/issuerelay">andrewbaisden/issuerelay</a>, the widget is published on npm as <a href="https://www.npmjs.com/package/@issuerelay/widget"><code>@issuerelay/widget</code></a>, and it's running in production on my portfolio website right now.</p>
<p>I won't paste the whole codebase into this article. The repository has every file, and the setup guide walks through installation step by step. Instead, I'll show you the small pieces of code that carry the important ideas, explain what each one does, and share what I learned while building, testing, and deploying it.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/41588a15-244b-496e-b48e-a284a26d2526.png" alt="The IssueRelay support widget open on a website, showing the Ask a question, Report a bug, and Suggest a feature options" style="display: block;" width="1440" height="900" loading="lazy">

<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-table-of-contents">Table of Contents</a></p>
</li>
<li><p><a href="#heading-prerequisites">Prerequisites</a></p>
</li>
<li><p><a href="#heading-how-an-ai-support-system-can-help-any-website">How an AI Support System Can Help Any Website</a></p>
</li>
<li><p><a href="#heading-what-well-build">What We'll Build</a></p>
</li>
<li><p><a href="#heading-what-is-jev">What Is Jev?</a></p>
</li>
<li><p><a href="#heading-the-tech-stack">The Tech Stack</a></p>
</li>
<li><p><a href="#heading-how-a-report-travels-through-the-system">How a Report Travels Through the System</a></p>
</li>
<li><p><a href="#heading-how-to-deploy-your-own-issuerelay">How to Deploy Your Own IssueRelay</a></p>
</li>
<li><p><a href="#heading-running-it-on-a-real-website">Running It on a Real Website</a></p>
</li>
<li><p><a href="#heading-testing-it-end-to-end-and-what-i-learned">Testing It End to End (and What I Learned)</a></p>
</li>
<li><p><a href="#heading-how-it-was-built-phases-and-ai-assisted-development">How It Was Built: Phases and AI Assisted Development</a></p>
</li>
<li><p><a href="#heading-publishing-the-widget-to-npm">Publishing the Widget to npm</a></p>
</li>
<li><p><a href="#heading-what-is-next">What Is Next</a></p>
</li>
<li><p><a href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow along and deploy your own copy, you should have:</p>
<ul>
<li><p><strong>Working knowledge of React, Next.js, and TypeScript:</strong> the platform uses the Next.js App Router, and the widget is a React component.</p>
</li>
<li><p><strong>Node.js 24 and pnpm:</strong> installed if you want to run the project locally or use the command that creates your GitHub App.</p>
</li>
<li><p><strong>A GitHub account:</strong> plus the repository for the website or app where you want to install the widget. Confirmed bugs become issues there.</p>
</li>
<li><p><strong>A Vercel account:</strong> The free Hobby plan is enough. You'll add a Neon PostgreSQL database through Vercel's marketplace, and Neon also has a free plan.</p>
</li>
<li><p><strong>A TypeSafe account:</strong> at <a href="https://typesafe.ai">typesafe.ai</a> for Jev, the AI model that triages reports. You need an API key from the <a href="https://console.typesafe.ai/keys">TypeSafe console</a> before any report can become a GitHub issue.</p>
</li>
<li><p><strong>A React website:</strong> where you can add a component. A Next.js site is the easiest place to start.</p>
</li>
<li><p><strong>Optional: a Resend account:</strong> if you want account emails such as password resets.</p>
</li>
</ul>
<p>You don't need to be an AI expert to follow along. Jev is used through a small, typed SDK, and most of the interesting work is ordinary web engineering: databases, validation, authentication, and webhooks.</p>
<h2 id="heading-how-an-ai-support-system-can-help-any-website">How an AI Support System Can Help Any Website</h2>
<p>A support system sounds like something only big companies need, but the problem it solves shows up on almost every website:</p>
<ul>
<li><p><strong>Portfolio sites</strong> get messages from recruiters, questions about projects, and reports about pages that break on a particular browser.</p>
</li>
<li><p><strong>SaaS products</strong> get bug reports mixed with billing questions and feature requests, and each one needs a different person or process.</p>
</li>
<li><p><strong>Documentation sites</strong> get "this example doesn't work" reports that are really bugs in the product.</p>
</li>
<li><p><strong>Open source projects</strong> get users who won't open a GitHub issue themselves but will happily click a button on the website.</p>
</li>
<li><p><strong>Client sites</strong> you built for someone else get feedback that the client forwards to you days later with no details.</p>
</li>
</ul>
<p>A good system gives you one place where every report arrives, keeps each report safe even when other services fail, and sorts reports so you spend your time on the ones that matter.</p>
<p>The AI part helps with the sorting, but it should never be in charge. A model can be confidently wrong, and a public GitHub issue isn't something you want to create on a guess. So IssueRelay follows one simple rule throughout: AI recommends, a human confirms, and code enforces the rules.</p>
<h2 id="heading-what-well-build">What We'll Build</h2>
<p>Here's the journey of a single report through IssueRelay:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/69c55783-997b-4f80-876b-22721315e898.png" alt="Here is the journey of a single report through IssueRelay" style="display: block;" width="1672" height="941" loading="lazy">

<p>A visitor opens the widget on your site and picks a topic:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/2a45c808-676c-4a10-8b55-93a0e393e262.png" alt="The widget open on a demo site with its three topics: Ask a question, Report a bug, and Suggest a feature" style="display: block;" width="2560" height="1720" loading="lazy">

<p>They describe the problem and can optionally leave a name and email so you can follow up:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/cdcf5b75-44da-47f5-9eeb-21583dcfae0c.png" alt="The Report a bug form in the widget with a message, a name, and an email address filled in" style="display: block;" width="2560" height="1720" loading="lazy">

<p>The widget sends the report to your IssueRelay platform, which saves it and replies with a support reference the visitor can quote later:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/39e72c56-5dc2-4c76-bc86-fc9d65e71bc4.png" alt="The widget confirming Message received with the support reference SUP-9" style="display: block;" width="2560" height="1720" loading="lazy">

<p>From there, the report becomes a ticket in your dashboard. Jev classifies it, you review it, and if it is a real bug, one click creates a GitHub issue in your repository.</p>
<p>Here's the full feature list:</p>
<ul>
<li><p><strong>An embeddable widget:</strong> Built as a React component inside a Shadow DOM, so it needs no CSS setup and never clashes with your site's styles. It works in the Next.js App Router and under a strict Content Security Policy.</p>
</li>
<li><p><strong>Durable intake:</strong> Every report is stored in PostgreSQL before anything else runs, with protection against duplicates, per project rate limits, and a list of allowed site addresses.</p>
</li>
<li><p><strong>Bounded AI triage:</strong> Jev recommends a type and severity from the message alone.</p>
</li>
<li><p><strong>A private dashboard:</strong> With filters, classification history, and human review decisions that are stored separately from the AI's output.</p>
</li>
<li><p><strong>Careful GitHub escalation:</strong> Issues are created by a GitHub App only after an owner confirms a preview, and contact details never leave IssueRelay.</p>
</li>
<li><p><strong>Two way sync:</strong> Closing or reopening the issue on GitHub updates the ticket through signed webhooks.</p>
</li>
<li><p><strong>Self hosting:</strong> A Deploy button, a first run setup page, and a settings page make it possible to run your own copy without touching the database.</p>
</li>
</ul>
<h2 id="heading-what-is-jev">What Is Jev?</h2>
<p>Jev is a model from <a href="https://typesafe.ai">TypeSafe</a> that's built for what TypeSafe calls "System One" tasks: quick, bounded judgments as opposed to long, open ended writing.</p>
<p>Instead of asking a model to write a paragraph and then trying to parse it, you give Jev some state and a set of questions, and each question has a fixed list of possible answers. Jev picks an answer for each question and returns the probability it assigned to every option.</p>
<p>That shape is exactly what support triage needs. A ticket is a bug, a question, a feature request, a billing problem, or spam. It's low, medium, high, or critical. There's no text for the model to invent, no prompt injection that can make it write an issue title, and no free text to clean up afterwards. The output is a label and a number, and your code can check both.</p>
<p>It's also cheap and fast. At the time of writing, TypeSafe lists Jev at $42 per billion input tokens, and a support message is a few dozen tokens. The IssueRelay integration sends Jev only the visitor's message and the topic they picked. It never sends names, email addresses, ticket IDs, or anything else that identifies a person.</p>
<h2 id="heading-the-tech-stack">The Tech Stack</h2>
<p>IssueRelay is built with a modern TypeScript stack, and it's the same stack I use for my own projects. If you've read <a href="https://www.freecodecamp.org/news/author/andrewbaisden/">my other articles</a>, a lot of it will look familiar:</p>
<ul>
<li><p><strong>Next.js 16 (App Router) and React 19</strong> for the platform and the dashboard</p>
</li>
<li><p><strong>Strict TypeScript</strong> everywhere, with <strong>Zod</strong> checking every input that crosses a trust boundary: public API requests, environment variables, AI output, and GitHub webhook payloads</p>
</li>
<li><p><strong>PostgreSQL with Drizzle ORM</strong> and reviewed SQL migrations</p>
</li>
<li><p><strong>Better Auth</strong> for dashboard accounts</p>
</li>
<li><p><strong>The official TypeSafe SDK</strong> for Jev, and <strong>Octokit</strong> for the GitHub App</p>
</li>
<li><p><strong>Vitest, React Testing Library, and Playwright</strong> for tests, and <strong>Biome</strong> for linting and formatting</p>
</li>
<li><p><strong>pnpm workspaces</strong> to hold everything in one monorepo</p>
</li>
<li><p><strong>Vercel, Neon, and Resend</strong> in production</p>
</li>
</ul>
<p>The monorepo is split into small packages, each with a strict job:</p>
<table>
<thead>
<tr>
<th>Package</th>
<th>Responsibility</th>
</tr>
</thead>
<tbody><tr>
<td><code>apps/web</code></td>
<td>The platform: the public ticket API, the dashboard, setup, and the GitHub webhook</td>
</tr>
<tr>
<td><code>packages/widget</code></td>
<td>The browser widget published to npm. It never imports server code.</td>
</tr>
<tr>
<td><code>packages/support-contracts</code></td>
<td>The request and response shapes shared by the widget and the API</td>
</tr>
<tr>
<td><code>packages/db</code></td>
<td>The Drizzle schema, migrations, and every database query</td>
</tr>
<tr>
<td><code>packages/ai</code></td>
<td>The Jev adapter, the triage service, and the routing policy</td>
</tr>
<tr>
<td><code>packages/github</code></td>
<td>The GitHub App client, issue drafts, the privacy gate, and webhook handling</td>
</tr>
<tr>
<td><code>packages/auth</code></td>
<td>Better Auth setup, sessions, and workspace membership checks</td>
</tr>
</tbody></table>
<p>The boundaries matter more than they might look like they do. React components never talk to GitHub, Jev, or the database directly. Browser code never contains a secret. The AI package can't import the database.</p>
<p>Keeping those lines strict made the system much easier to test and to reason about, and it's the reason the widget can be published to npm without dragging any server code along with it.</p>
<h2 id="heading-how-a-report-travels-through-the-system">How a Report Travels Through the System</h2>
<p>Let's follow one report from the visitor's browser all the way to a closed GitHub issue.</p>
<h3 id="heading-step-1-the-widget">Step 1: The Widget</h3>
<p>The widget is a normal React component that you install from npm:</p>
<pre><code class="language-shell">npm install @issuerelay/widget
</code></pre>
<p>Then you render it once, for example from a client component in your root layout:</p>
<pre><code class="language-typescript">"use client";

import {
  HttpSupportSubmissionClient,
  SupportWidget,
} from "@issuerelay/widget";

const submissionClient = new HttpSupportSubmissionClient({
  apiBaseUrl: "https://your-issuerelay.vercel.app",
});

export function Support() {
  return (
    &lt;SupportWidget
      projectKey="pk_your_project_key"
      submissionClient={submissionClient}
      theme="system"
      position="bottom-right"
    /&gt;
  );
}
</code></pre>
<p><code>HttpSupportSubmissionClient</code> is the part that talks to your platform. It posts each report to your IssueRelay API without cookies or credentials, and it gives every report a submission ID so that a retry after a network error doesn't create a second ticket.</p>
<p><code>SupportWidget</code> is the button and panel your visitors see. The <code>projectKey</code> tells the platform which project the report belongs to. It's public identification, not a password, so it's safe to put in your site's code. The real protection is on the server, which only accepts reports from the site addresses you list for that project.</p>
<p>The <code>"use client"</code> line is there because the submission client is created in the browser. In the Next.js App Router, you wrap the widget in your own small client component like this and render that component from your layout.</p>
<p>Under the hood, the widget renders inside a Shadow DOM with its own bundled styles, so your site doesn't need Tailwind or a CSS import, and your styles can't accidentally restyle it.</p>
<p>You don't have to write this code by hand, either. IssueRelay's project settings page shows this exact snippet with your platform address and project key already filled in.</p>
<h3 id="heading-step-2-save-first-think-later">Step 2: Save First, Think Later</h3>
<p>When the report reaches the API, the first thing IssueRelay does is save it. Not classify it, not send it anywhere, just store it in PostgreSQL inside a transaction.</p>
<p>This is the most important design decision in the whole system. AI providers have outages. GitHub has outages. If the platform called Jev before saving the report and Jev timed out, the visitor's message would be lost, and they would never know.</p>
<p>So the rule is simple: <strong>a report is accepted only after it's safely stored, and a failure in any later step can never erase it.</strong> If Jev is down, the ticket waits in the dashboard until you run triage again.</p>
<p>Before saving, the API checks a few things:</p>
<ul>
<li><p>The request body matches the shared Zod contract, so bad input is rejected with a clear error.</p>
</li>
<li><p>The project key exists, and the request's origin is one of the project's allowed site addresses.</p>
</li>
<li><p>The project is under its rate limit.</p>
</li>
<li><p>The submission ID hasn't been used before. A repeated submission returns the original ticket reference instead of creating a duplicate.</p>
</li>
</ul>
<h3 id="heading-step-3-triage-with-jev">Step 3: Triage with Jev</h3>
<p>Once a ticket is stored, the triage service asks Jev to classify it. Here's the heart of the Jev adapter, from <code>packages/ai/src/jev-classifier.ts</code> (trimmed a little for space):</p>
<pre><code class="language-typescript">const response = await this.client.systemOne({
  state: {
    message: input.message,
    category_hint: input.categoryHint ?? null,
  },
  questions: {
    ticket_type: choice(
      "What kind of support ticket is this? The visitor-selected category hint is a weak signal, not ground truth: judge from the message content.",
      {
        question: "The visitor asks how something works or what something is.",
        bug: "Something is broken, errors, or behaves incorrectly.",
        feature_request: "The visitor requests new functionality or an improvement.",
        spam: "Unsolicited advertising, scams, or irrelevant bulk content.",
        // ...account, billing, feedback, and other
      },
    ),
    severity: choice("How urgent is this ticket?", {
      low: "Minor inconvenience, cosmetic issue, or general question.",
      medium: "Broken functionality with a workaround, or a routine request.",
      high: "Major functionality unavailable, no workaround, time-sensitive.",
      critical: "Security breach, data loss, privacy exposure, or billing harm.",
    }),
  },
});
</code></pre>
<p><code>systemOne</code> is the TypeSafe SDK call for bounded questions. The <code>state</code> object is everything Jev is allowed to see: the message and the topic the visitor picked.</p>
<p>Notice what's missing. There's no name, no email, and no ticket ID, because none of them help with classification and all of them would be private data leaving your platform.</p>
<p>Each <code>choice</code> defines one question and its possible answers. The descriptions next to each label tell Jev what the label means. The ticket type question also tells Jev to treat the visitor's chosen topic as a weak hint, because people often pick "Report a bug" for a question, or "Ask a question" for something that's clearly broken.</p>
<p>What comes back isn't trusted automatically. The adapter validates the response with a Zod schema, checks that both answers are labels from the allowed lists, and uses the probability Jev gave to the chosen type label as the confidence score.</p>
<p>If that probability is missing or outside the range 0 to 1, the result is rejected, and the ticket stays in review instead of getting a made up number.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/2530f001-0850-4603-8694-5125766b421c.png" alt="A ticket in the dashboard after triage: Jev classified it as a medium severity bug with a confidence of 1.00 and recommended it for GitHub" style="display: block;" width="2560" height="2802" loading="lazy">

<h3 id="heading-step-4-code-makes-the-decisions">Step 4: Code Makes the Decisions</h3>
<p>Jev recommends a type and a severity. It doesn't decide where a ticket goes or whether it becomes a GitHub issue. That job belongs to plain functions in <code>packages/ai/src/policy.ts</code>:</p>
<pre><code class="language-typescript">export function routeForType(type: TicketType): TicketRoute {
  switch (type) {
    case "bug":
      return "engineering";
    case "feature_request":
      return "product";
    case "spam":
      return "ignore";
    default:
      return "support";
  }
}

export function evaluateGitHubEscalation(input: {
  type: TicketType;
  route: TicketRoute;
  confidence: number;
}): EscalationEvaluation {
  const reasons: string[] = [];
  if (input.type !== "bug") reasons.push(`type is ${input.type}, not bug`);
  if (input.route !== "engineering") reasons.push(`route is ${input.route}, not engineering`);
  if (!(input.confidence &gt;= GITHUB_ESCALATION_CONFIDENCE_THRESHOLD)) {
    reasons.push(`confidence ${input.confidence} is below ${GITHUB_ESCALATION_CONFIDENCE_THRESHOLD}`);
  }
  return { eligible: reasons.length === 0, reasons };
}
</code></pre>
<p><code>routeForType</code> maps each ticket type to a queue. Bugs go to engineering, feature requests go to product, spam is quarantined, and everything else goes to support. Because this is a normal <code>switch</code> statement, you can read it, test it, and change it without touching the AI.</p>
<p><code>evaluateGitHubEscalation</code> decides whether a ticket is even allowed to become a GitHub issue. It must be a bug, it must be in the engineering queue, and its confidence must be at least 0.9. Instead of returning a bare <code>true</code> or <code>false</code>, it collects the reasons a ticket failed, which the dashboard shows so you always know why the <strong>Create GitHub issue</strong> button is missing.</p>
<p>The 0.9 threshold lives in one configuration file with a comment that says it's an uncalibrated starting point, not a measured accuracy. I wanted that to be honest in the code: a model score of 0.99 doesn't mean the model is right 99 percent of the time.</p>
<h3 id="heading-step-5-human-review-in-the-dashboard">Step 5: Human Review in the Dashboard</h3>
<p>Every ticket lands in a private dashboard. The projects page shows how many tickets are in each state:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/f9381b89-d338-48d9-8c47-e8f872674416.png" alt="The dashboard projects page showing two projects with ticket counts for each workflow state" style="display: block;" width="2560" height="1720" loading="lazy">

<p>Each project has a ticket list with filters for status, route, type, severity, and reference:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/f44934f1-fdd9-4c6a-ad46-f5a32d6d056f.png" alt="The ticket list for a project, with filters and a table of tickets showing their status, route, AI type, severity, and confidence" style="display: block;" width="2560" height="1720" loading="lazy">

<p>Opening a ticket shows the visitor's report, the current AI classification, the full classification history, and a timeline of everything that happened. You can run triage again, resolve the ticket, or record a review decision that changes the route, the status, or the GitHub recommendation.</p>
<p>One detail I care about: human decisions are stored in their own table, with the author and a required reason. The AI's history is never rewritten. If you override Jev, you can still see exactly what Jev said and when, which is important when you want to know how well the model is really doing.</p>
<p>The dashboard is protected by Better Auth, and every read and write is scoped to a workspace. Mutations require a same origin request, and only workspace owners can publish to GitHub.</p>
<h3 id="heading-step-6-from-bug-report-to-github-issue">Step 6: From Bug Report to GitHub Issue</h3>
<p>When a ticket passes the policy, the dashboard shows a preview of the exact issue that will be created:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/6b77db48-f122-4dcf-9da5-d858f7a6eb5d.png" alt="The GitHub escalation section showing a preview of the issue title and body, with the visitor's name and email absent from the issue" style="display: block;" width="2560" height="3434" loading="lazy">

<p>Look closely at that screenshot. The visitor left their name and email, and both are visible in the dashboard above, but neither appears anywhere in the issue preview.</p>
<p>That's not a coincidence. Before any issue is created, the report passes through a privacy gate in <code>packages/github/src/privacy.ts</code> that looks for email addresses, phone numbers, card numbers, private keys, API tokens, JSON web tokens, and password assignments. It also checks the report against the contact details the visitor submitted, so "Hi, Sam Visitor here" can't leak a name into a public issue. If anything is found, the preview is blocked and nothing is published.</p>
<p>When you click <strong>Create GitHub issue</strong>, a few more safeguards run:</p>
<ul>
<li><p><strong>A GitHub App, not a personal token:</strong> The App is installed only on the repositories you choose, with permission to write issues and read metadata, and nothing else.</p>
</li>
<li><p><strong>Claim first, then create:</strong> The ticket is marked as <code>creating</code> in the database before GitHub is called, so two clicks can never create two issues.</p>
</li>
<li><p><strong>A hidden marker:</strong> Each issue body ends with an opaque HTML comment tied to the ticket. If a request times out and the result is unknown, IssueRelay searches the repository for that exact marker from its own App before it ever tries again. It never blindly retries an issue it might already have created.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/dc142997-48e0-4b03-8046-6ad5fe4e3320.png" alt="The ticket after escalation, showing the linked GitHub issue and the escalation events in the timeline" style="display: block;" width="2560" height="2200" loading="lazy">

<p>Here's a real issue that IssueRelay created on my portfolio's public repository from a visitor report. It was created by the App's bot, labelled <code>bug</code>, and contains the report and the AI's classification, but no contact details:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/ec38844a-648e-4b98-b971-45edcadcf968.png" alt="A real GitHub issue created by the IssueRelay bot on a public repository, with a summary, the report, context, and a note that contact details are never published" style="display: block;" width="2560" height="2200" loading="lazy">

<h3 id="heading-step-7-keeping-github-and-the-dashboard-in-sync">Step 7: Keeping GitHub and the Dashboard in Sync</h3>
<p>The last piece closes the loop. When you close the issue on GitHub, GitHub sends a webhook to IssueRelay, and the ticket moves to resolved. Reopen the issue and the ticket goes back into the queue.</p>
<p>A webhook endpoint is public by definition, so the first thing it does is prove the request really came from GitHub. This is the verification function from <code>packages/github/src/webhook-auth.ts</code>:</p>
<pre><code class="language-typescript">export function verifyWebhookSignature(input: {
  secret: string;
  rawBody: Uint8Array;
  signatureHeader: string | null;
}): boolean {
  const { secret, rawBody, signatureHeader } = input;
  if (!secret || !signatureHeader?.startsWith("sha256=")) {
    return false;
  }
  const hex = signatureHeader.slice("sha256=".length);
  if (!/^[0-9a-f]{64}$/.test(hex)) return false;
  const expected = createHmac("sha256", secret).update(rawBody).digest();
  const actual = Buffer.from(hex, "hex");
  if (expected.length !== actual.length) return false;
  return timingSafeEqual(expected, actual);
}
</code></pre>
<p>GitHub signs every delivery with a secret that only GitHub and your platform know, and sends the signature in the <code>X-Hub-Signature-256</code> header. This function computes its own HMAC SHA256 signature over the <strong>raw request bytes</strong> and compares the two.</p>
<p>Two details are easy to get wrong. First, the signature has to be computed over the exact bytes GitHub sent, before any JSON parsing, because parsing and reformatting would change the bytes. Second, the comparison uses <code>timingSafeEqual</code>, which takes the same amount of time whether the first byte or the last byte differs, so an attacker can't guess the signature one character at a time by measuring response times. The function also returns <code>false</code> for every kind of failure without saying which one, so it leaks nothing.</p>
<p>After the signature check, IssueRelay stores each delivery ID, so a repeated delivery is ignored. It updates only an issue that belongs to the matching App installation and repository, and it applies events in the order they happened on GitHub, not the order they arrived.</p>
<h2 id="heading-how-to-deploy-your-own-issuerelay">How to Deploy Your Own IssueRelay</h2>
<p>You can run your own IssueRelay on Vercel and Neon in about 15 minutes. The complete walkthrough, including troubleshooting, is in <a href="https://github.com/andrewbaisden/issuerelay/blob/main/docs/SELF_HOSTING.md">docs/SELF_HOSTING.md</a>. Here's the short version.</p>
<h3 id="heading-step-1-deploy"><strong>Step 1: Deploy</strong></h3>
<p>The recommended path is the <strong>Deploy with Vercel</strong> button in the README. It copies the repository into your GitHub account, adds a Neon database, and asks for three random secrets.</p>
<p>The first build fails on purpose because Vercel's clone screen has no Root Directory setting, so you set Root Directory to <code>apps/web</code> in the project settings and redeploy. The production build then creates every database table for you.</p>
<p>The guide also describes a <strong>Fork and Import</strong> path that makes future updates a single click, but that path hasn't been tested end to end yet.</p>
<h3 id="heading-step-2-run-the-setup-page"><strong>Step 2: Run the Setup Page</strong></h3>
<p>Open <code>/setup</code> on your new site. It only works while the database has no accounts and you enter the <code>SETUP_TOKEN</code> you created during the deploy, so nobody who finds your URL first can claim your platform. It creates your owner account and your first project, then shows your widget key and the ready to paste widget code.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/6b09f257-4b29-41bd-8c6b-e95db8200504.png" alt="The first run setup page with fields for the setup token, owner account, workspace, site name, and site addresses" style="display: block;" width="2560" height="2464" loading="lazy">

<p>The site address field starts with <code>http://localhost:3000</code>, which is where a Next.js app runs on your computer. Add your live address too, such as <code>https://my-site.vercel.app</code> or your own domain. If you forget, the widget will politely tell visitors "We couldn't send your message," so this is the first thing to check when a report doesn't arrive.</p>
<h3 id="heading-step-3-create-the-github-app"><strong>Step 3: Create the GitHub App</strong></h3>
<p>Setting up a GitHub App by hand has a few easy mistakes in it. The worst one is forgetting to subscribe to the Issues event, which I did myself during testing. So IssueRelay includes a command that creates the App for you from a manifest:</p>
<pre><code class="language-shell">pnpm github:create-app --platform https://your-issuerelay.vercel.app
</code></pre>
<p>This opens GitHub in your browser with everything already filled in: a private App with permission to write issues and read metadata, subscribed to the Issues event, with its webhook pointing at your platform.</p>
<p>You click <strong>Create GitHub App</strong>, GitHub redirects back to a temporary local server started by the command, and the command writes the App ID, private key, and webhook secret to a file that git ignores. It never prints them in your terminal. The terminal then lists the next setup phase.</p>
<h3 id="heading-step-4-add-your-keys-and-redeploy"><strong>Step 4: Add Your Keys and Redeploy</strong></h3>
<p>Add the three GitHub App values and your <code>TYPESAFE_API_KEY</code> to your Vercel project's environment variables, then redeploy. Jev is required for GitHub issues: without it, reports still arrive in your dashboard, but none can become an issue.</p>
<h3 id="heading-step-5-connect-your-repository"><strong>Step 5: Connect Your Repository</strong></h3>
<p>Install the App on the repository of the website where the widget will live, then open your project's <strong>Settings</strong> page in the dashboard and connect it. The page asks GitHub which installation and repository ID belong to that name, so a typo can't link the wrong repository.</p>
<img src="https://cdn.hashnode.com/uploads/covers/5f46a01aa639932bd830f982/d7ca9ddf-9774-4031-a67e-51f4fbec8781.png" alt="The project settings page with the widget key, the ready to paste widget code, the allowed site addresses, and the connected GitHub repository" style="display: block;" width="2560" height="2626" loading="lazy">

<h3 id="heading-step-6-install-the-widget"><strong>Step 6: Install the Widget</strong></h3>
<p>Install the widget on your site with the code from the settings page, and send your first report.</p>
<p>To keep your copy up to date later, pull changes from the main repository. The guide covers the one time step needed for copies made with the Deploy button, because those copies are not GitHub forks.</p>
<h2 id="heading-running-it-on-a-real-website">Running It on a Real Website</h2>
<p>A demo is one thing, but I wanted to use IssueRelay for real, so the widget now runs on my portfolio at <a href="https://andrewbaisden.com/">andrewbaisden.com</a>:</p>
<img src="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/2cd31d2a-b973-4e6b-a37e-6fd2fb203b7b.png" alt="The IssueRelay widget open in the corner of the author's portfolio website, over an illustrated London street scene" style="display: block;" width="2880" height="1800" loading="lazy">

<p>The website design will likely change, so if you're reading this article in the future, previous builds can be found on my GitHub.</p>
<p>Installing it taught me a few things. My portfolio was still on React 18 for its tests, while the App Router was already rendering with React 19. So I upgraded it to React 19 first and made sure every existing test passed before adding the widget. The widget matches the site's light and dark themes, sits in the bottom right corner, and has its own unit test and browser test in the portfolio repository.</p>
<p>Then I tested it like a visitor would. I sent three real reports from the live site: a question, a bug, and a feature request. Jev classified all three the way I intended, with scores between 0.95 and 1.00, and the policy routed them to support, engineering, and product. The bug became issue #3 in my public portfolio repository, which is the issue shown in the screenshot earlier. I had included my name and email with that report, and neither appears in the public issue.</p>
<h2 id="heading-testing-it-end-to-end-and-what-i-learned">Testing It End to End (and What I Learned)</h2>
<p>I didn't want a project that only worked on my machine, so testing was part of every phase instead of something saved for the end.</p>
<p>The test suite has several layers:</p>
<ul>
<li><p><strong>Unit tests</strong> for the widget, the API contract, the AI policy, the privacy gate, the setup page, and more. There are 180 of them, and none need a database.</p>
</li>
<li><p><strong>Database integration tests</strong> that run against a separate PostgreSQL test database, including concurrency tests that prove two clicks can't create two GitHub issues.</p>
</li>
<li><p><strong>Browser tests with Playwright</strong> that start their own servers on separate ports, with a separate database that is recreated for every run, so a test can never touch real data. One of those servers runs against an empty database to test the first run setup page.</p>
</li>
<li><p><strong>A package check</strong> that builds the exact npm tarball and installs it into a Vite app with a strict Content Security Policy and into a Next.js app, both outside the monorepo, then submits a report in each.</p>
</li>
<li><p><strong>A live journey test</strong> with 20 checks against a real GitHub App and a throwaway repository: submit a report, triage it, preview it, create the issue, check that no private data was published, close the issue on GitHub and wait for the webhook, reopen it, and check the timeline.</p>
</li>
</ul>
<p>I ran that live journey three times: first against my local machine through a tunnel, then against production, and finally against a completely fresh copy that I deployed by following only the setup guide. All three passed 20 out of 20.</p>
<p>More interesting than the passes, though, are the problems each stage uncovered:</p>
<ul>
<li><p><strong>The Issues event is easy to forget:</strong> The first time I created a GitHub App by hand, it had no event subscriptions, so GitHub never told IssueRelay when issues closed. That mistake is why the <code>create-app</code> command exists.</p>
</li>
<li><p><strong>Visitors mention their own names:</strong> A report like "Sarah here, the page is broken" from a visitor named Sarah would have put her name in a public issue. The privacy gate now compares every report against the contact details that came with it.</p>
</li>
<li><p><strong>Zod and strict CSP don't mix in the browser:</strong> Zod 4 briefly tests whether it can use <code>new Function</code>, and sites with a strict Content Security Policy report that as a violation. I removed Zod from the widget and wrote small validation checks instead, with a test that proves they agree with the server's Zod schemas on 270 form combinations.</p>
</li>
<li><p><strong>Vercel's clone flow has no Root Directory option, and Vercel picks the framework only once:</strong> My fresh deploy failed twice: once because Vercel built the repository root, and once because the framework was still set to "Other." The repository now pins Next.js in <code>vercel.json</code>, and the guide warns about the first failure.</p>
</li>
<li><p><strong>Deploy button copies aren't forks:</strong> A plain <code>git pull</code> from the main repository refuses to merge, so the guide now has a one time command to connect a copy to the main repository.</p>
</li>
<li><p><strong>GitHub issues need Jev:</strong> I originally listed Jev as optional. A careful review of the guide showed that without it, no real report can reach the confidence threshold. The guide and the settings page now say so clearly.</p>
</li>
<li><p><strong>Log noise matters:</strong> Every database connection logged an SSL warning at error level, which made a healthy deployment look broken. The fix was to spell out the SSL mode the driver was already using, so the warning disappeared while the certificate checks stayed exactly the same.</p>
</li>
</ul>
<p>The lesson that stuck with me most: <strong>deploying from your own documentation, word for word, finds bugs that no test will.</strong> Every one of the deployment problems above was invisible to the automated tests and obvious the moment a real person followed the guide.</p>
<h2 id="heading-how-it-was-built-phases-and-ai-assisted-development">How It Was Built: Phases and AI Assisted Development</h2>
<p>IssueRelay was built in small phases, and each phase ended with a written handoff before the next one could start:</p>
<table>
<thead>
<tr>
<th>Phase</th>
<th>Outcome</th>
</tr>
</thead>
<tbody><tr>
<td>0</td>
<td>Product definition, architecture, decisions, security, and test plans</td>
</tr>
<tr>
<td>1 and 2</td>
<td>Monorepo foundation, domain model, PostgreSQL schema, and seed data</td>
</tr>
<tr>
<td>3 and 4</td>
<td>The widget, a demo site, and the public ticket API</td>
</tr>
<tr>
<td>5 and 6</td>
<td>AI triage with Jev and the operator dashboard</td>
</tr>
<tr>
<td>7 and 8</td>
<td>Confirmed GitHub escalation and signed webhook sync</td>
</tr>
<tr>
<td>9</td>
<td>Live validation of the full journey in a throwaway repository</td>
</tr>
<tr>
<td>10</td>
<td>Production hardening</td>
</tr>
<tr>
<td>11 and 12</td>
<td>Validating and publishing the widget to npm</td>
</tr>
<tr>
<td>Deploy</td>
<td>Vercel, Neon, and Resend in production</td>
</tr>
<tr>
<td>13</td>
<td>Installing the widget on my portfolio</td>
</tr>
<tr>
<td>14 and 15</td>
<td>Dogfooding (ongoing)</td>
</tr>
<tr>
<td>16</td>
<td>Self hosting: the Deploy button, the setup page, project settings, and the App manifest command</td>
</tr>
</tbody></table>
<h3 id="heading-my-developer-setup">My Developer Setup</h3>
<p>I did most of the work in the terminal. My setup is:</p>
<ul>
<li><p>Ghostty as my terminal, running Claude Code, Codex, and OpenCode</p>
</li>
<li><p>Cursor as my editor</p>
</li>
<li><p>The native desktop apps for ChatGPT, Claude, and OpenCode</p>
</li>
</ul>
<p>My main model for building IssueRelay was <strong>Claude Opus 5.5</strong> in Claude Code. For code reviews and for checking a phase before I signed it off, I used other models, including <strong>GPT-6 Sol</strong> and Grok, along with various other frontier and free models.</p>
<p>A second model reading the same code with fresh eyes caught real problems. For example, a Grok review of Phases 7 and 8 raised 15 findings. Seven were valid, including a race in claiming issue creation and issue markers that could be guessed, and all seven were fixed before I moved on. Three more were partly valid and five were deferred with written reasons.</p>
<p>Anthropic's newly released <strong>Sonnet 5.5</strong> and OpenAI's <strong>GPT-6.1 Sol</strong> weren't used in this project.</p>
<h3 id="heading-how-better-prompts-improved-the-codebase">How Better Prompts Improved the Codebase</h3>
<p>The biggest improvement in quality didn't come from a smarter model. It came from giving the model better instructions and a better structure to work in. Here is what worked:</p>
<ul>
<li><p><strong>One phase at a time:</strong> Each prompt asked for exactly one phase with a clear outcome, and the AI wasn't allowed to start the next phase until I approved it. Small, reviewable changes were much easier to check than one giant feature.</p>
</li>
<li><p><strong>A plan before any code:</strong> For bigger phases I asked for a plan first ("Create a plan and then go ahead with it once I approve it"). Reading a plan takes two minutes. Unpicking a wrong implementation takes an afternoon.</p>
</li>
<li><p><strong>Rules that live in the repository:</strong> An <code>AGENTS.md</code> file holds the project's rules, such as "persist an accepted ticket before external AI or GitHub calls," "never publish contact data to GitHub," and "do not blindly retry an ambiguous GitHub issue creation." Every AI session reads it, so the rules don't depend on me remembering to repeat them.</p>
</li>
<li><p><strong>Honest reporting:</strong> The instructions say never to report an unrun check as passing, and every handoff records the commands that were run and their real results, including failures.</p>
</li>
<li><p><strong>Clear conditions for committing:</strong> Prompts like "commit and push when tests pass and there are no other issues" meant the full test suite ran before anything reached the main branch.</p>
</li>
<li><p><strong>Asking for proof, not promises:</strong> Instead of asking "does self hosting work?", I asked the AI to verify it by following the guide on a fresh deployment. That single request uncovered seven documentation and configuration problems.</p>
</li>
<li><p><strong>Feeding back real use:</strong> When I deployed a test site myself and wrote down everything that confused me, those notes went straight back into the guide, the setup page, and the settings page.</p>
</li>
</ul>
<h2 id="heading-publishing-the-widget-to-npm">Publishing the Widget to npm</h2>
<p>The widget is the only part of IssueRelay that is published, as <a href="https://www.npmjs.com/package/@issuerelay/widget"><code>@issuerelay/widget</code></a>. Everything else stays private inside the monorepo.</p>
<p>I didn't want to publish something that only worked inside my own workspace, so the release check builds the exact tarball that npm will receive and inspects it.</p>
<p>It must contain only five files. It must not reference private packages, Node built ins, environment variables, or anything that looks like a key. It must then install and work in two brand new apps outside the repository, one of them under a strict Content Security Policy, with zero policy violations.</p>
<p>Releases are published from GitHub Actions with npm trusted publishing and provenance, so there is no long lived npm token to leak.</p>
<p>The result is a package of about 10 KB compressed that needs no CSS setup and depends only on React and React Hook Form. The <a href="https://github.com/andrewbaisden/issuerelay/tree/main/packages/widget#readme">widget README</a> documents every prop.</p>
<h2 id="heading-what-is-next">What Is Next</h2>
<p>IssueRelay is complete for self hosting, and I'm using it every day on my portfolio. Some things I would like to explore next:</p>
<ul>
<li><p><strong>A hosted version</strong> of IssueRelay, so you could sign up and add the widget without deploying anything yourself</p>
</li>
<li><p><strong>Testing the Fork and Import path</strong> end to end so it can become the recommended way to deploy</p>
</li>
<li><p>Ideas from the roadmap, such as detecting duplicate reports, linking several reports to one issue, notifications, and syncing GitHub comments</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this tutorial, you saw how to build an AI support system that turns scattered website feedback into reviewed tickets and routes confirmed bugs to GitHub. Along the way, you learned how to:</p>
<ul>
<li><p>Build an embeddable React widget that works on any site without CSS setup or style clashes</p>
</li>
<li><p>Save every report before calling any external service, so provider outages never lose data</p>
</li>
<li><p>Use Jev for bounded, validated classification that returns labels and probabilities instead of free text</p>
</li>
<li><p>Keep routing and publishing decisions in plain, testable code, with a human in the loop</p>
</li>
<li><p>Create GitHub issues safely with a GitHub App, a privacy gate, and a marker that prevents duplicates</p>
</li>
<li><p>Keep GitHub and your dashboard in sync with signed, verified webhooks</p>
</li>
<li><p>Deploy your own copy on Vercel and Neon, and test it end to end, including against your own documentation</p>
</li>
</ul>
<p>The best way to understand IssueRelay is to try it. You can <a href="https://github.com/andrewbaisden/issuerelay">explore the code on GitHub</a>, deploy your own copy with the <a href="https://github.com/andrewbaisden/issuerelay/blob/main/docs/SELF_HOSTING.md">self hosting guide</a>, and add the widget to your site with <code>npm install @issuerelay/widget</code> from <a href="https://www.npmjs.com/package/@issuerelay/widget">npm</a>. If it helps you, a star on the repository is always appreciated.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Node.js and Express.js Handbook for Beginners – Servers, Routes, Routers, and Views Explained ]]>
                </title>
                <description>
                    <![CDATA[ Node.js is a runtime environment for executing JavaScript outside the web browser. From small scripts to large-scale back-end applications, Node.js provides the APIs and tools you need to build JavaSc ]]>
                </description>
                <link>https://www.freecodecamp.org/news/nodejs-and-expressjs-handbook-for-beginners/</link>
                <guid isPermaLink="false">6abe2c47229f69b03c107a96</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Express ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Oluwatobi Sofela ]]>
                </dc:creator>
                <pubDate>Thu, 01 Oct 2026 09:47:51 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5fc16e412cae9c5b190b6cdd/da9c2a49-21e8-4b9a-8dc3-adac2dcf82d0.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Node.js is a runtime environment for executing JavaScript outside the web browser. From small scripts to large-scale back-end applications, Node.js provides the APIs and tools you need to build JavaScript applications for a variety of environments.</p>
<p>But learning Node.js can feel overwhelming. With so many APIs, packages, tools, and concepts to understand, it’s easy to feel lost.</p>
<p>That’s why this book focuses on the fundamental Node.js concepts you need to build practical applications without unnecessary distractions. You’ll learn how Node.js works, how to use its built-in APIs, and how to create applications that interact with files, URLs, events, HTTP requests, and more.</p>
<p>You’ll also learn how Express.js simplifies many common server-side tasks. We’ll explore routes, routers, controllers, views, and other concepts that help you organize and build web applications more efficiently.</p>
<p>Whether you’re learning backend development for the first time or expanding your JavaScript skills beyond the browser, this guide is designed to give you a clear and practical foundation for building with Node.js and Express.js.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-what-you-should-already-know">What You Should Already Know</a></p>
</li>
<li><p><a href="#heading-the-tools-youll-need">The Tools You'll Need</a></p>
</li>
<li><p><a href="#heading-what-exactly-is-nodejs">What Exactly Is Node.js?</a></p>
<ul>
<li><p><a href="#heading-create-a-new-directory-for-your-project">Create a New Directory for Your Project</a></p>
</li>
<li><p><a href="#heading-create-a-packagejson-file">Create apackage.jsonFile</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-why-nodejs">Why Node.js?</a></p>
<ul>
<li><p><a href="#heading-1-create-a-javascript-file">1. Create a JavaScript File</a></p>
</li>
<li><p><a href="#heading-2-write-your-javascript-program">2. Write your JavaScript Program</a></p>
</li>
<li><p><a href="#heading-3-run-your-javascript-program">3. Run your JavaScript Program</a></p>
</li>
<li><p><a href="#heading-4-automatically-rerun-your-javascript-program">4. Automatically Rerun Your JavaScript Program</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-nodes-module-support">Node's Module Support</a></p>
</li>
<li><p><a href="#heading-create-http-servers-with-nodejs">Create HTTP Servers with Node.js</a></p>
<ul>
<li><p><a href="#heading-initialize-a-new-instance-of-the-http-server-object">Initialize a New Instance of the HTTPServerObject</a></p>
</li>
<li><p><a href="#heading-configure-the-systems-port-where-the-server-should-run">Configure the System's Port Where the Server Should Run</a></p>
</li>
<li><p><a href="#heading-configure-the-server-to-respond-to-client-requests">Configure the Server to Respond to Client Requests</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-what-exactly-is-expressjs">What Exactly Is Express.js?</a></p>
<ul>
<li><p><a href="#heading-1-install-express">1. Install Express</a></p>
</li>
<li><p><a href="#heading-2-use-expressjs-to-configure-the-projects-nodejs-web-server">2. Use Express.js to Configure the Project's Node.js Web Server</a></p>
</li>
<li><p><a href="#heading-3-run-the-expressjs-web-server">3. Run the Express.js Web Server</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-raw-nodejs-code-vs-expressjs-code">Raw Node.js Code vs. Express.js Code</a></p>
<ul>
<li><p><a href="#heading-example-1-use-raw-nodejs-to-handle-web-requests">Example 1: Use raw Node.js to Handle Web Requests</a></p>
</li>
<li><p><a href="#heading-example-2-use-expressjs-to-handle-web-requests">Example 2: Use Express.js to Handle Web Requests</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-important-stuff-to-know-about-creating-expressjs-web-servers-in-nodejs">Important Stuff to Know About Creating Express.js Web Servers in Node.js</a></p>
<ul>
<li><p><a href="#heading-its-common-to-call-applisten-last">It's Common to Callapp.listen()Last</a></p>
</li>
<li><p><a href="#heading-you-can-set-the-port-number-using-environment-variables">You Can Set the Port Number Using Environment Variables</a></p>
</li>
<li><p><a href="#heading-common-expressjs-response-methods">Common Express.js Response Methods</a></p>
</li>
<li><p><a href="#heading-expresss-response-methods-do-not-terminate-the-http-request-handlers-execution">Express's Response Methods Do Not Terminate the HTTP Request Handler's Execution</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-what-is-a-route-in-expressjs">What Is a Route in Express.js?</a></p>
<ul>
<li><p><a href="#heading-syntax-of-a-route-in-express">Syntax of a Route in Express</a></p>
</li>
<li><p><a href="#heading-middleware-vs-route-handler">Middleware vs. Route Handler</a></p>
</li>
<li><p><a href="#heading-route-examples-in-expressjs">Route Examples in Express.js</a></p>
</li>
<li><p><a href="#heading-important-things-to-know-about-the-next-parameter">Important Things to Know About thenextParameter</a></p>
</li>
<li><p><a href="#heading-categories-of-middleware-in-expressjs">Categories of Middleware in Express.js</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-what-is-the-expressrouter-method">What Is the express.Router() Method?</a></p>
<ul>
<li><p><a href="#heading-create-a-directory-for-the-routers">Create a Directory for the Routers</a></p>
</li>
<li><p><a href="#heading-create-the-route-files">Create the Route Files</a></p>
</li>
<li><p><a href="#heading-create-a-mini-app-for-the-book-related-routes-and-middleware">Create a Mini-App for the Book-Related Routes and Middleware</a></p>
</li>
<li><p><a href="#heading-time-to-practice-with-routers">Time to Practice with Routers</a></p>
</li>
<li><p><a href="#heading-update-the-main-express-application">Update the Main Express Application</a></p>
</li>
<li><p><a href="#heading-run-your-expressjs-application">Run your Express.js Application</a></p>
</li>
<li><p><a href="#heading-important-things-to-know-about-express-routers">Important Things to Know About Express Routers</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-what-is-a-view-in-expressjs">What Is a View in Express.js?</a></p>
<ul>
<li><p><a href="#heading-what-are-static-views-in-expressjs">What Are Static Views in Express.js?</a></p>
</li>
<li><p><a href="#heading-what-are-dynamic-views-in-expressjs">What Are Dynamic Views in Express.js?</a></p>
</li>
</ul>
</li>
<li><p><a href="#heading-overview">Overview</a></p>
<ul>
<li><a href="#heading-dive-deeper-into-nodejs-and-expressjs">Dive Deeper into Node.js and Express.js</a></li>
</ul>
</li>
</ul>
<h2 id="heading-what-you-should-already-know">What You Should Already Know</h2>
<p>This guide is for readers who know basic JavaScript and want to start building web applications with Node.js and Express.js. You'll get the most value from it if you're familiar with:</p>
<ul>
<li><p>JavaScript fundamentals, including variables, functions, arrays, and objects.</p>
</li>
<li><p>Basic asynchronous JavaScript, including callbacks, promises, and <code>async</code>/<code>await</code>.</p>
</li>
<li><p>Basic HTML, including links, forms, and input elements.</p>
</li>
<li><p>Using a terminal to navigate folders and run commands.</p>
</li>
</ul>
<p>You don't need previous experience with Node.js or Express.js. Familiarity with installing npm packages is helpful, but the examples will guide you through the commands you need.</p>
<h2 id="heading-the-tools-youll-need">The Tools You'll Need</h2>
<p>Before you begin, have a code editor, a web browser, and the following installed:</p>
<ul>
<li><p>Node.js 24.15.0 or later.</p>
</li>
<li><p>npm 11.14.0 or later.</p>
</li>
</ul>
<p>Check your installed versions by running:</p>
<pre><code class="language-console">node --version &amp;&amp; npm --version
</code></pre>
<p>Node.js includes npm, but the bundled version may be older than the one listed here. Check both versions and update npm separately if needed. The <a href="https://codesweetly.com/package-manager-explained">CodeSweetly package manager guide</a> explains how to install, update, and check these tools.</p>
<p>The file-creation commands assume an environment with <code>mkdir</code> and <code>touch</code> available, such as Bash or zsh on macOS or Linux, Git Bash on Windows, or a Linux shell through Windows Subsystem for Linux (WSL). You can also create the files and folders directly in your editor.</p>
<p>Let's get started with Node.js.</p>
<h2 id="heading-what-exactly-is-nodejs">What Exactly Is Node.js?</h2>
<p>Node.js is not a framework or language. Instead, it is an <a href="https://codesweetly.com/asynchronous-javascript">asynchronous</a>, <a href="https://developer.mozilla.org/en-US/docs/Learn_web_development/Core/Scripting/Events">event</a>-driven environment that includes tools such as:</p>
<ul>
<li><p>JavaScript engine (Google's V8)</p>
</li>
<li><p>Module system (CommonJS and ES modules)</p>
</li>
<li><p>Operating system APIs (<code>os</code>)</p>
</li>
<li><p>Filesystem access (<code>fs</code>)</p>
</li>
<li><p>Network servers (<code>http</code>, <code>net</code>, <code>https</code>)</p>
</li>
<li><p>Memory management tools</p>
</li>
<li><p>Event loop</p>
</li>
</ul>
<p>These components make up Node.js's core infrastructure, enabling JavaScript to run outside of browsers.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61672d1653401f641ba159b4/2ed752ef-64a7-43a8-9323-53ee00665048.jpg" alt="Node.js explained" style="display: block;" width="1920" height="1920" loading="lazy">

<p>The image above illustrates Node.js as a well-equipped runtime environment providing the infrastructure to build and run any scale of JavaScript applications outside the browser, including servers, CLIs, scripts, and full-stack applications.</p>
<p>Let's discuss the points highlighted in the image by building applications with Node.js and Express.js. To begin, create the project directory.</p>
<h3 id="heading-create-a-new-directory-for-your-project">Create a New Directory for Your Project</h3>
<p>Use the <code>mkdir</code> CLI command to create a new project directory as follows:</p>
<pre><code class="language-console">mkdir codesweetly-nodejs-app-001
</code></pre>
<p><strong>Note:</strong> You can use any name you prefer. In this guide, we'll use <code>codesweetly-nodejs-app-001</code> for demonstration.</p>
<p>Afterward, navigate to your project directory using the command line.</p>
<pre><code class="language-console">cd codesweetly-nodejs-app-001
</code></pre>
<h3 id="heading-create-a-packagejson-file">Create a <code>package.json</code> File</h3>
<p>Use npm to initialize a <a href="https://codesweetly.com/package-json-file-explained"><code>package.json</code> file</a> after navigating into the project directory.</p>
<pre><code class="language-console">npm init -y
</code></pre>
<p>Next, use the following command to delete the optional <code>main</code> field from <code>package.json</code>:</p>
<pre><code class="language-console">npm pkg delete main
</code></pre>
<p><strong>Tip:</strong> The <code>main</code> field in <code>package.json</code> identifies a package's entry point when another program loads the package. We do not need it for this project because we'll run our scripts directly. Leaving it in place is also harmless.</p>
<h2 id="heading-why-nodejs">Why Node.js?</h2>
<p>JavaScript was originally created for web browsers, but other environments also provide the infrastructure to execute it.</p>
<p>Node's 2009 release provided an environment for running JavaScript outside the web browser. For example, let's create a script to run from our system's terminal.</p>
<h3 id="heading-1-create-a-javascript-file">1. Create a JavaScript File</h3>
<p>Create the JavaScript file you want Node to run.</p>
<p>In a shell that supports <code>touch</code>, such as Bash or zsh, use the following command. Otherwise, create the file in your code editor:</p>
<pre><code class="language-console">touch console.js
</code></pre>
<h3 id="heading-2-write-your-javascript-program">2. Write your JavaScript Program</h3>
<p>Open the newly created JavaScript file and write your program:</p>
<pre><code class="language-javascript">console.log("=== Hello from the CodeSweetly Team! ===");
console.log("We hope you have fun Coding Sweetly with Node.js.");
console.log("Thank you for being part of the CodeSweetly community.");
console.log("=== Keep coding. Keep creating. Keep shipping. ===");
</code></pre>
<h3 id="heading-3-run-your-javascript-program">3. Run your JavaScript Program</h3>
<p>Installing Node.js makes the <code>node</code> command available for running a Node application from your command line.</p>
<pre><code class="language-console">node console.js
</code></pre>
<ul>
<li><p><code>node</code>: The command for running Node.js scripts or the REPL.</p>
</li>
<li><p><code>console.js</code>: The JavaScript file you want Node to run.</p>
</li>
</ul>
<p>You can also add the command to the <code>"scripts"</code> field of your project's <code>package.json</code> file:</p>
<pre><code class="language-json">{
  "scripts": {
    "start": "node console.js",
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  }
}
</code></pre>
<p>With this script in place, you can run your JavaScript program from your terminal like this:</p>
<pre><code class="language-console">npm run start
</code></pre>
<p>Once you execute your script, Node will print the file's output to your terminal. It will look like this:</p>
<pre><code class="language-console">$ npm run start

&gt; codesweetly-nodejs-app-001@1.0.0 start
&gt; node console.js

=== Hello from the CodeSweetly Team! ===
We hope you have fun Coding Sweetly with Node.js.
Thank you for being part of the CodeSweetly community.
=== Keep coding. Keep creating. Keep shipping. ===
</code></pre>
<p>As you can see, we've successfully executed JavaScript outside a web browser. That's precisely what Node.js helps us with. It is an asynchronous, event-driven runtime environment for running JavaScript code outside the web browser. You can also automate rerunning your program. Let's discuss how.</p>
<h3 id="heading-4-automatically-rerun-your-javascript-program">4. Automatically Rerun Your JavaScript Program</h3>
<p>By default, Node.js requires you to manually rerun your JavaScript file each time you make changes.</p>
<p>Repeating the manual process of executing your application as you make changes can be burdensome. Luckily, Node provides the <code>--watch</code> flag for automating the process:</p>
<pre><code class="language-console">node --watch filename.extension
</code></pre>
<p>The snippet above uses the <code>--watch</code> flag to start Node.js in watch mode. This causes Node to re-execute the specified script whenever you update any of the files in its dependency graph.</p>
<ul>
<li><p><code>node</code>: The command for running Node.js scripts or the REPL.</p>
</li>
<li><p><code>--watch</code>: The flag for activating Node's watch mode.</p>
</li>
<li><p><code>filename.extension</code>: The script you want Node to execute.</p>
</li>
</ul>
<p><strong>Tip:</strong> Stop the running process using <code>Ctrl + C</code> on Windows, macOS, or Linux.</p>
<p>The <code>--watch</code> flag, by default, watches the entry point and all the modules it depends on. In other words, the watch command causes Node to monitor:</p>
<ul>
<li><p>The entry file (<code>filename.extension</code>)</p>
</li>
<li><p>All files imported by the entry file</p>
</li>
<li><p>All files imported in those imports</p>
</li>
<li><p>And so on through the whole dependency graph</p>
</li>
</ul>
<p>Node's default watch mode does not watch unrelated files. If you want Node to watch other files, use the <code>--watch-path</code> flag:</p>
<pre><code class="language-console">node --watch-path=./src --watch-path=./tests filename.extension
</code></pre>
<p>The <code>--watch-path</code> flag, in the snippet above, tells Node to watch all files in the <code>src</code> and <code>tests</code> directories, even if they are not in the entry point's dependency graph.</p>
<ul>
<li><p><code>node</code>: The command for running Node.js scripts or the REPL.</p>
</li>
<li><p><code>--watch-path</code>: The flag for specifying the path you want Node to watch for changes.</p>
</li>
<li><p><code>filename.extension</code>: The script you want Node to execute.</p>
</li>
</ul>
<p><strong>Tip:</strong></p>
<ul>
<li><p>The <code>--watch-path</code> flag causes Node to ignore the dependency graph's modules unless they are part of <code>--watch-path</code>. Instead, Node.js will watch only the exact paths you specified, and nothing else.</p>
</li>
<li><p><code>--watch-path</code> enables watch mode itself. If you also pass <code>--watch</code>, Node still watches only the specified paths.</p>
</li>
<li><p><code>--watch-path</code> is supported on macOS and Windows, but not Linux. On Linux, use <code>--watch</code> to monitor the entry file and its dependencies.</p>
</li>
<li><p>Watch commands do not reload the browser automatically. They simply detect file changes, so Node reruns the program you specified. As such, if your program sends data to browsers, you will need to refresh the browser yourself or use a third-party tool for auto-reloading.</p>
</li>
</ul>
<p>Node.js supports two module systems. Let's learn about them.</p>
<h2 id="heading-nodes-module-support">Node's Module Support</h2>
<p>Node.js supports both CommonJS (<code>.cjs</code>) and ECMAScript (<code>.mjs</code>) <a href="https://codesweetly.com/javascript-modules-tutorial">modules</a>. This allows you to use your preferred module type to create Node.js applications.</p>
<p>For example, below is a <code>script.mjs</code> JavaScript file. Node will treat it as an ECMAScript module because it has a <code>.mjs</code> file extension.</p>
<p><code>script.mjs</code></p>
<pre><code class="language-javascript">import http from "node:http";
</code></pre>
<p>On the other hand, Node will regard the <code>script.cjs</code> JavaScript file below as a CommonJS module because it has a <code>.cjs</code> file extension.</p>
<p><code>script.cjs</code></p>
<pre><code class="language-javascript">const http = require("node:http");
</code></pre>
<p>Suppose you want to specify the module type for the <code>.js</code> files in your project. In that case, specify a <code>type</code> field in your <code>package.json</code> file like so:</p>
<p><code>package.json</code></p>
<pre><code class="language-json">{
  "scripts": {
    "start": "node console.js",
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "type": "module",
  "license": "ISC"
}
</code></pre>
<p>The <code>"type": "module"</code> field in the snippet above makes Node treat <code>.js</code> files governed by this <code>package.json</code> as ES modules. A nested <code>package.json</code> establishes its own scope. <code>.mjs</code> and <code>.cjs</code> files retain their respective module types.</p>
<p>Set the <code>"type"</code> field to <code>"commonjs"</code> to make Node treat <code>.js</code> files in that scope as CommonJS.</p>
<p>Some notes:</p>
<ul>
<li><p>The ES module system is the official standard for JavaScript.</p>
</li>
<li><p>Kevin Dangoor started the project that became CommonJS in January 2009, before JavaScript had an official standard module system.</p>
</li>
<li><p>ES modules became part of the ECMAScript standard in 2015. CommonJS remains supported in Node.js.</p>
</li>
</ul>
<p>In this guide, we'll mainly use Node.js with ES modules, since ES modules are JavaScript's standard module system. To follow the examples, make sure the <code>"type"</code> field in your <code>package.json</code> file is set to <code>"module"</code>. You can do this by running the following command from your project directory:</p>
<pre><code class="language-console">npm pkg set type=module
</code></pre>
<p>When relevant, we'll compare CommonJS syntax.</p>
<p>Let's now discuss using Node.js to create web servers that receive and respond to requests from browsers.</p>
<h2 id="heading-create-http-servers-with-nodejs">Create HTTP Servers with Node.js</h2>
<p>An HTTP server lets your JavaScript application handle requests from clients, such as browsers, and send responses.</p>
<p>There are three main steps to configuring an app's HTTP server:</p>
<ol>
<li><p>Create a new instance of the HTTP <code>Server</code> object.</p>
</li>
<li><p>Specify the system's port where you want the server to run.</p>
</li>
<li><p>Define how the server should respond to client requests.</p>
</li>
</ol>
<p>Let's discuss the three steps in detail. To start, create an ES module for your project.</p>
<pre><code class="language-console">touch server.js
</code></pre>
<p>Afterward, open the newly created module and initialize a new instance of the HTTP <code>Server</code> object.</p>
<h3 id="heading-initialize-a-new-instance-of-the-http-server-object">Initialize a New Instance of the HTTP <code>Server</code> Object</h3>
<p>Node provides the <code>createServer</code> method for creating an instance of the HTTP <code>Server</code> object (<code>http.Server</code>).</p>
<p>You can use it in your project by importing it from Node's <code>http</code> module as follows:</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import { createServer } from "node:http";

const server = createServer();
</code></pre>
<p>Here's what's going on:</p>
<ul>
<li><p><code>import</code> statement: Imports the <code>createServer</code> API from Node's <code>http</code> library to the <code>server.js</code> ES module.</p>
</li>
<li><p><code>server</code>: A variable for storing the HTTP <code>Server</code> object that the <code>createServer()</code> function outputs.</p>
</li>
</ul>
<p>Here's the CommonJS alternative:</p>
<p><code>server.cjs</code></p>
<pre><code class="language-javascript">const http = require("node:http");

const server = http.createServer();
</code></pre>
<p>Once you have created the local HTTP <code>Server</code> object, specify the server's port.</p>
<h3 id="heading-configure-the-systems-port-where-the-server-should-run">Configure the System's Port Where the Server Should Run</h3>
<p>The HTTP <code>Server</code> object provides a <code>listen()</code> method to configure the port on which the server should run and accept client requests.</p>
<h4 id="heading-syntax">Syntax</h4>
<pre><code class="language-javascript">import { createServer } from "node:http";

const server = createServer();

server.listen(port, hostname, backlog, callback);
</code></pre>
<p>This form of the <code>listen()</code> method accepts the following arguments:</p>
<ul>
<li><p><code>port</code>: (number) The port number where the server should run and listen for client requests. If omitted, the operating system will assign any unused port. You can use <code>server.address().port</code> to retrieve the port the server is listening on after it starts listening for client connections.</p>
</li>
<li><p><code>hostname</code>: (string) The hostname or IP address on which the server should accept client connections. If omitted, the server will default to either an unspecified <a href="https://en.wikipedia.org/wiki/IPv6_address#Unspecified_address">IPv6 (<code>::</code>)</a> address or an <a href="https://en.wikipedia.org/wiki/0.0.0.0">IPv4 (<code>0.0.0.0</code>)</a> address. These unspecified addresses bind to all network interfaces for the applicable address family. You can use <code>server.address().address</code> to retrieve the bound IP address once it starts listening for client connections.</p>
</li>
<li><p><code>backlog</code>: (number) Maximum length of the pending connections' queue. 511 is the default value.</p>
</li>
<li><p><code>callback</code>: (function) The function to execute once the server starts listening for client requests.</p>
</li>
</ul>
<h4 id="heading-example">Example</h4>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import { createServer } from "node:http";

const server = createServer();

server.listen(3000, "127.0.0.1", 511, () =&gt; {
  const info = server.address();
  console.log(`Server running at http://${info.address}:
${info.port}/`);
});
</code></pre>
<p>Here's what's going on:</p>
<ul>
<li><p><code>import</code> statement: Imports the <code>createServer</code> API from Node's <code>http</code> library to the <code>server.js</code> ES module.</p>
</li>
<li><p><code>server</code>: A variable for storing the HTTP <code>Server</code> object that the <code>createServer()</code> function outputs.</p>
</li>
<li><p><code>server.listen()</code>: Starts the server to listen for client connections. (Tip: The method emits a <a href="https://nodejs.org/api/net.html#event-listening"><code>listening</code></a> event once the server starts successfully.)</p>
</li>
</ul>
<p>Here's the CommonJS alternative:</p>
<p><code>server.cjs</code></p>
<pre><code class="language-javascript">const http = require("node:http");

const server = http.createServer();

server.listen(3000, "127.0.0.1", 511, () =&gt; {
  const info = server.address();
  console.log(`Server running at http://${info.address}:
${info.port}/`);
});
</code></pre>
<h4 id="heading-what-is-the-127001-address">What is the <code>127.0.0.1</code> address?</h4>
<p>The <code>127.0.0.1</code> address is an IPv4 loopback address that refers to your local computer. The hostname <code>localhost</code> also refers to your local computer, but it may resolve to <code>127.0.0.1</code> or the IPv6 loopback address, <code>::1</code>. You can use it as follows:</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import { createServer } from "node:http";

const server = createServer();

server.listen(3000, "localhost", 511, () =&gt; {
  console.log("Server running at http://localhost:3000/");
});
</code></pre>
<p>If you run this server and visit its web address, the browser will wait for a response because we have not yet set up a request handler. Let's configure that now.</p>
<h3 id="heading-configure-the-server-to-respond-to-client-requests">Configure the Server to Respond to Client Requests</h3>
<p>The <code>createServer()</code> method accepts a <code>requestListener</code> callback that is invoked automatically whenever the server receives an HTTP request. Node allows you to use this callback to respond to requests.</p>
<h4 id="heading-syntax">Syntax</h4>
<p>The <code>createServer()</code> method accepts two optional arguments. Here's the syntax:</p>
<pre><code class="language-javascript">import { createServer } from "node:http";

const server = createServer(options, callback);
</code></pre>
<ul>
<li><p><code>options</code>: An object for customizing the server's behavior.</p>
</li>
<li><p><code>callback</code>: The <code>requestListener</code> function for handling and responding to client requests. It accepts two parameters:</p>
</li>
</ul>
<pre><code class="language-javascript">import { createServer } from "node:http";

const server = createServer(options, function (request, response) {
  // the requestListener function's body
});
</code></pre>
<ul>
<li><p><code>request</code> parameter: An <code>http.IncomingMessage</code> object that provides details about the client request.</p>
</li>
<li><p><code>response</code> parameter: An <code>http.ServerResponse</code> object for responding to the client requests.</p>
</li>
</ul>
<p>Providing the <code>requestListener</code> callback function as <code>createServer</code>'s second argument causes Node.js to automatically register it as a listener for the <a href="https://nodejs.org/api/http.html#event-request"><code>"request"</code></a> event. So, the syntax above is equivalent to:</p>
<pre><code class="language-javascript">import { createServer } from "node:http";

const server = createServer(options);

server.on("request", function (request, response) {
  // the requestListener function's body
});
</code></pre>
<p><code>server.on("request", callback)</code> tells the server to listen for a request event and execute the callback on such an event.</p>
<h4 id="heading-example">Example</h4>
<p><code>server.js</code></p>
<pre><code class="language-javascript">// Add the Node.js HTTP module
import { createServer } from "node:http";

// Specify the hostname and port to run the server
const hostname = "localhost";
const port = 3000;

// Create a new Server instance with a requestListener callback
const server = createServer((req, res) =&gt; {
  res.statusCode = 200; // Set an OK success (200) response status code
  res.setHeader("Content-Type", "text/plain"); // Define the media type of the response data
  res.end("Hello World!"); // Specify the response data and close the response stream
});

// Run the server on the specified port and hostname
server.listen(port, hostname, () =&gt; {
  console.log(`Server running at http://${hostname}:
${port}/`);
});
</code></pre>
<p>The snippet above used the <code>requestListener</code> callback function's response parameter to configure the server to respond to client requests. Here's the <code>server.on("request", callback)</code> alternative:</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">// Add the Node.js HTTP module
import { createServer } from "node:http";

// Specify the hostname and port to run the server
const hostname = "localhost";
const port = 3000;

// Create a new Server instance
const server = createServer();

// Listen for a request event and execute the requestListener callback
server.on("request", (req, res) =&gt; {
  res.statusCode = 200; // Set an OK success (200) response status code
  res.setHeader("Content-Type", "text/plain"); // Define the media type of the response data
  res.end("Hello World!"); // Specify the response data and close the response stream
});

// Run the server on the specified port and hostname
server.listen(port, hostname, () =&gt; {
  console.log(`Server running at http://${hostname}:
${port}/`);
});
</code></pre>
<p>Now that your server is set up and the port configured, you can run the application.</p>
<pre><code class="language-console">node server.js
</code></pre>
<ul>
<li><p><code>node</code>: The command for running Node.js scripts or the REPL.</p>
</li>
<li><p><code>server.js</code>: The JavaScript file you want Node to run.</p>
</li>
</ul>
<p>While the server is running, if users request the app's resource at the server's web address, they will see a <code>Hello World!</code> response as illustrated in the following image.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61672d1653401f641ba159b4/29085aef-058e-44f3-8e9a-fad24dc387b5.jpg" alt="The browser displays the &quot;Hello World!&quot; text at http://localhost:3000/" style="display: block;" width="1920" height="1080" loading="lazy">

<p><strong>Tip:</strong> Stop the running process using <code>Ctrl + C</code> on Windows, macOS, or Linux.</p>
<p>Although the <code>node:http</code> module is Node.js's native API for handling HTTP requests, developers typically use frameworks to simplify the process. Some popular Node.js web frameworks include Express.js, Fastify, and Koa.js. Let's use Express.js as an example to see how a framework can simplify HTTP request handling in Node.</p>
<h2 id="heading-what-exactly-is-expressjs">What Exactly Is Express.js?</h2>
<p>Express.js is a web framework that simplifies server-side HTTP request handling in Node.js. It extends Node's HTTP module with built-in features such as routing and middleware, helping developers to build web applications and APIs efficiently without repetitive code. Here's how to use it in your Node.js project.</p>
<h3 id="heading-1-install-express">1. Install Express</h3>
<pre><code class="language-console">npm install express@5.2.1
</code></pre>
<h3 id="heading-2-use-expressjs-to-configure-the-projects-nodejs-web-server">2. Use Express.js to Configure the Project's Node.js Web Server</h3>
<p>Open the JavaScript server file and use Express.js to set up a web server:</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">// Add the Express module
import express from "express";

// Create a new Express application instance
const app = express();

// Set the port number where the server will run and listen for requests
const port = 3000;

// Create a route handler for GET requests to the "/" path
app.get("/", (req, res) =&gt; res.send("Hello, world!"));

// Run the server on the specified port
app.listen(port, () =&gt; {
  console.log(`Server running at http://localhost:${port}`);
});
</code></pre>
<p>Here's what the code above does:</p>
<ul>
<li><p>Creates an Express application instance to access Express APIs, such as routers and middleware, simplifying HTTP request handling in Node.js.</p>
</li>
<li><p>Uses Express's <code>app.get()</code> method to define how the server handles HTTP GET requests to the <code>/</code> route.</p>
</li>
<li><p>Uses Express's <code>res.send()</code> method to send an HTTP response and automatically set the appropriate headers based on the data type provided.</p>
</li>
<li><p>Uses Express's <code>app.listen()</code> method to start the Node.js HTTP server on a specific port and execute a callback when the server begins listening for client requests.</p>
</li>
</ul>
<p><strong>Tip:</strong></p>
<ul>
<li><p>In the statement <code>app.get("/", (req, res) =&gt; res.send("Hello, world!"))</code>,</p>
<ul>
<li><p><code>app.get()</code> is the Express routing method.</p>
</li>
<li><p><code>"/"</code> is the route path.</p>
</li>
<li><p><code>(req, res) =&gt; ...</code> is the route handler function.</p>
</li>
<li><p>The entire statement is the route (or route definition).</p>
</li>
</ul>
</li>
<li><p>The objects passed to an Express route handler's parameters (<code>req</code> and <code>res</code>) are enhanced versions of Node's <code>http.IncomingMessage</code> and <code>http.ServerResponse</code> objects. Express adds properties and helper methods to simplify handling HTTP requests and responses.</p>
</li>
<li><p>The order of route definitions matters. Express processes matching routes in the order they are defined. A handler can end the response or pass control to another handler using <code>next()</code>.</p>
</li>
</ul>
<h3 id="heading-3-run-the-expressjs-web-server">3. Run the Express.js Web Server</h3>
<p>Use the <code>node</code> command followed by the script's filename to run a Node.js script, including one that uses Express.js to handle HTTP requests.</p>
<pre><code class="language-console">node server.js
</code></pre>
<p>Open <code>http://localhost:3000</code> in your browser to see <code>Hello, world!</code>.</p>
<p><strong>Tip:</strong> Stop the server using <code>Ctrl + C</code> on Windows or <code>Control + C</code> on macOS.</p>
<h2 id="heading-raw-nodejs-code-vs-expressjs-code">Raw Node.js Code vs. Express.js Code</h2>
<p>While you can use Node's native HTTP API to handle web requests, it requires manual configuration, such as inspecting each request's method and URL, setting response headers, and converting objects to JSON.</p>
<p>Express abstracts repetitive request-handling logic into declarative methods, simplifying Node.js web server development.</p>
<p>Below are two examples comparing Node.js web server code written with the native HTTP module and with Express methods.</p>
<h3 id="heading-example-1-use-raw-nodejs-to-handle-web-requests">Example 1: Use raw Node.js to Handle Web Requests</h3>
<p>The following web server uses Node's built-in HTTP module to handle GET requests to two endpoints—home (<code>/</code>) and books (<code>/books</code>)—and return a 404 response for unmatched requests.</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import { createServer } from "node:http";
const port = 3000;

const server = createServer((req, res) =&gt; {
  if (req.method === "GET" &amp;&amp; req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("Welcome to the homepage!");
  } else if (req.method === "GET" &amp;&amp; req.url === "/books") {
    const books = [
      { id: 1, name: "Code React Sweetly" },
      { id: 2, name: "Creating NPM Package" },
    ];
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(books));
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("Page not found");
  }
});

server.listen(port, () =&gt; {
  console.log(`Raw Node server running at http://localhost:${port}`);
});
</code></pre>
<p>The snippet above uses Node's native <code>http</code> module to build a web server that accepts and responds to browser connections. In this raw Node.js example, you manually handle the following tasks:</p>
<ul>
<li><p><strong>Routing to the correct endpoint:</strong> <code>if (req.method === "..." &amp;&amp; req.url === "...")</code></p>
</li>
<li><p><strong>Response header configuration:</strong> <code>res.writeHead(...)</code></p>
</li>
<li><p><strong>JSON formatting:</strong> <code>JSON.stringify(...)</code></p>
</li>
</ul>
<p>Now, let's see how to build a similar web server using Express. Run these examples one at a time, replacing the contents of <code>server.js</code> and restarting the server.</p>
<h3 id="heading-example-2-use-expressjs-to-handle-web-requests">Example 2: Use Express.js to Handle Web Requests</h3>
<p>The following web server uses Express routes to handle GET requests to two endpoints—home (<code>/</code>) and books (<code>/books</code>)—and return a 404 response for unmatched requests.</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import express from "express";
const app = express();
const port = 3000;

app.get("/", (req, res) =&gt; {
  res.send("Welcome to the homepage!");
});

app.get("/books", (req, res) =&gt; {
  const books = [
    { id: 1, name: "Code React Sweetly" },
    { id: 2, name: "Creating NPM Package" },
  ];
  res.json(books);
});

app.use((req, res) =&gt; {
  res.status(404).send("Page not found");
});

app.listen(port, () =&gt; {
  console.log(`Express server running at http://localhost:${port}`);
});
</code></pre>
<p>The snippet above uses Express.js to build a web server that accepts and responds to browser connections. Express simplifies the following tasks:</p>
<ul>
<li><p><strong>Routing logic:</strong> Express.js provides simple route declarations like <code>app.get()</code>, <code>app.post()</code>, and <code>app.delete()</code>, eliminating the need for complex conditional ogic to check <code>req.url</code> and <code>req.method</code> for each route.</p>
</li>
<li><p><strong>Response header configuration:</strong> Express's <code>res.send()</code> method automatically sets appropriate response headers based on the response body. Use <code>res.status()</code> when you need to set a status code, as in the 404 handler above.</p>
</li>
<li><p><strong>JSON formatting:</strong> Express's <code>res.json()</code> method automatically converts JavaScript objects into valid JSON responses, handling serialization and headers for you.</p>
</li>
</ul>
<h2 id="heading-important-stuff-to-know-about-creating-expressjs-web-servers-in-nodejs">Important Stuff to Know About Creating Express.js Web Servers in Node.js</h2>
<p>Keep the following key points in mind when creating Express.js servers in your Node.js project.</p>
<h3 id="heading-its-common-to-call-applisten-last">It's Common to Call <code>app.listen()</code> Last</h3>
<p>It's common to call <code>app.listen()</code> last in an Express.js app. This way, all your routes, middleware, and error handlers are set up before the server starts listening for requests.</p>
<h3 id="heading-you-can-set-the-port-number-using-environment-variables">You Can Set the Port Number Using Environment Variables</h3>
<p>To read the port number from an environment variable, replace the existing <code>port</code> declaration with the following:</p>
<pre><code class="language-javascript">const port = process.env.PORT || 3000;
</code></pre>
<p>The above snippet instructs Node to use the <code>PORT</code> environment variable's value, or default to <code>3000</code> if it's unset or empty. In a shell such as Bash, the following command sets <code>PORT</code> to <code>8000</code> for this run of the server:</p>
<pre><code class="language-console">PORT=8000 node server.js
</code></pre>
<h3 id="heading-common-expressjs-response-methods">Common Express.js Response Methods</h3>
<p>Here are some common response methods you'll use in Express.js:</p>
<ul>
<li><p><code>res.send()</code>: Send an HTTP response to the client and automatically set the appropriate response headers based on the data type provided as the method's argument.</p>
</li>
<li><p><code>res.json()</code>: Send JSON responses to the client and automatically set the response's <code>Content-Type</code> header to <code>application/json</code>.</p>
</li>
<li><p><code>res.redirect()</code>: Redirect the client's request to a different URL.</p>
</li>
<li><p><code>res.render()</code>: Render a template engine's view and send the resulting HTML string to the client.</p>
</li>
<li><p><code>res.status()</code>: Set the response's HTTP status code without ending the request-response cycle. You can chain other response methods to it, for example, <code>res.status(404).send("404 Error: Page not found")</code>. You do not need to call this method to use the default status code of <code>200</code>.</p>
</li>
<li><p><code>res.end()</code>: End the response. When called without a data argument, it sends no additional response body data. It can also accept data to send before ending the response.</p>
</li>
</ul>
<h3 id="heading-expresss-response-methods-do-not-terminate-the-http-request-handlers-execution">Express's Response Methods Do Not Terminate the HTTP Request Handler's Execution</h3>
<p>While response methods like <code>res.send()</code> close the HTTP request-response cycle, they do not end the execution of the route handler function.</p>
<p><strong>Here's an example:</strong></p>
<pre><code class="language-javascript">app.get("/", (req, res) =&gt; {
  // This sends a text response to the client and ends the request-response cycle, but does not end the route handler's execution
  res.send("Hello, client!");

  // This logs the string to the console because the function is still running
  console.log("Hello, devs!");

  // This will cause an error because the request-response cycle is closed, so you cannot send additional responses to the client during the callback's execution
  res.send("Hello, client again!");
});
</code></pre>
<p>The <code>console.log()</code> statement in the example above works because the request handler is still running. The <code>res.send("Hello, client!")</code> line ends the response to that request. It does not stop the callback's execution.</p>
<p>Note that the <code>app.get(...)</code> code in the snippet above is called an Express route. But what exactly is a route in Express.js? Let's discuss it now.</p>
<h2 id="heading-what-is-a-route-in-expressjs">What Is a Route in Express.js?</h2>
<p>A route in Express.js consists of an HTTP method, a URL path, and a chain of one or more middleware functions for processing client requests to an endpoint.</p>
<p><strong>Tip:</strong></p>
<ul>
<li><p>An endpoint consists of an HTTP method and a URL path. (Endpoint = HTTP method + URL path)</p>
</li>
<li><p>The route includes an HTTP method, a URL path, and the server-side logic that handles client requests. (Route = Server HTTP method + Server URL path + handler function)</p>
</li>
</ul>
<h3 id="heading-syntax-of-a-route-in-express">Syntax of a Route in Express</h3>
<pre><code class="language-javascript">app.METHOD(PATH, HANDLER);
</code></pre>
<ul>
<li><p><code>app</code>: An Express application instance that provides access to Express APIs, including methods and middleware, to simplify HTTP request handling in Node.js.</p>
</li>
<li><p><code>METHOD</code>: A lowercase HTTP request method, such as <code>get</code>, <code>post</code>, or <code>delete</code>.</p>
</li>
<li><p><code>PATH</code>: The URL path the route will handle. It can be a string or a regular expression. Express 4 also supports string patterns whose syntax differs in Express 5.</p>
</li>
<li><p><code>HANDLER</code>: The callback (or middleware) function that Express executes when the request and route endpoints correspond. The handler may be:</p>
<ul>
<li><p>A single function</p>
</li>
<li><p>More than one function</p>
</li>
<li><p>An array of functions</p>
</li>
<li><p>A combination of an array of functions and individual function arguments.</p>
</li>
</ul>
</li>
</ul>
<p><strong>Tip:</strong></p>
<ul>
<li><p>You can use the <code>app.all()</code> method to set up handler functions that run for every supported HTTP request method on a specific <code>PATH</code>.</p>
</li>
<li><p>The <code>app.use()</code> method lets you set up middleware functions that can run for all HTTP request methods and paths when a request reaches them. If you specify a path argument, <code>app.use()</code> matches that path and its subpaths. For example, <code>/book</code> matches <code>/book</code>, <code>/book/dashboard</code>, and <code>/book/dashboard/author/202605</code>.</p>
</li>
</ul>
<h3 id="heading-middleware-vs-route-handler">Middleware vs. Route Handler</h3>
<p>Developers often use the term "route handler" to describe the final function responsible for resolving the request and sending the response, whereas preceding reusable functions are referred to as "middleware".</p>
<pre><code class="language-javascript">app.METHOD(PATH, MIDDLEWARE1, MIDDLEWARE2, HANDLER);
</code></pre>
<p><strong>Note:</strong> Express does not mandate distinct names or categories for functions attached to a route. From Express's perspective, they are all handler functions, with <code>next()</code> passing control from one to the next. However, developers often differentiate between middleware and route handlers to enhance code organization, readability, and communication.</p>
<ul>
<li><p>Middleware functions, often stored in a <code>/middlewares</code> directory, serve as utility components that perform cross-cutting or preparatory tasks such as authentication, validation, logging, and data loading. These functions are often reusable and typically invoke <code>next()</code> to pass control to the next function.</p>
</li>
<li><p>Route handlers, sometimes organized as controllers in a <code>/controllers</code> directory, contain the business logic that generates the endpoint's primary response, such as <code>getUserProfile</code>, <code>createBlogPost</code>, or <code>deleteAccount</code>. These functions may be specific to a route and usually conclude the request-response cycle by invoking methods such as <code>res.send()</code> or <code>res.json()</code>.</p>
</li>
</ul>
<h3 id="heading-route-examples-in-expressjs">Route Examples in Express.js</h3>
<p>Here are some examples of routes in Express.js.</p>
<h4 id="heading-express-route-with-a-single-handler-function">Express route with a single handler function</h4>
<pre><code class="language-javascript">app.get("/single/handler", (req, res) =&gt; {
  res.send("Request handled with a single handler function!");
});
</code></pre>
<p>The example above uses a single callback function to handle GET requests to the <code>GET /single/handler</code> endpoint. The handler function, in this case, is an inline controller. A common approach is to keep controllers in a <code>controllers</code> directory. This makes the code easier to test and maintain while keeping the route definition readable.</p>
<p><strong>Here's an example:</strong></p>
<p>The following example shows a <code>GET /single/handler</code> route with a modular controller that has been moved to its own module (<code>controllers/single-handler.js</code>). This approach separates route definitions from the request-handling logic that generates the endpoint's response.</p>
<pre><code class="language-javascript">import express from "express";
import * as controller from "./controllers/single-handler.js";

const app = express();
const port = 3000;

app.get("/single/handler", controller.singleHandler);

app.listen(port, () =&gt; {
  console.log(`Express server running at http://localhost:${port}`);
});
</code></pre>
<p>Below is an example of a controller file that contains only the <code>singleHandler</code> handler function.</p>
<p><code>controllers/single-handler.js</code></p>
<pre><code class="language-javascript">function singleHandler(req, res) {
  res.send("Request handled with a single handler function!");
}

export { singleHandler };
</code></pre>
<p><strong>Tip:</strong> A controller is a route handler or group of handlers that manages requests for specific endpoints. Controllers are often placed in separate modules to improve code organization and maintain a clear separation of concerns.</p>
<h4 id="heading-express-route-with-multiple-middleware-functions">Express route with multiple middleware functions</h4>
<pre><code class="language-javascript">app.get(
  "/multiple/middleware",
  (req, res, next) =&gt; {
    console.log("First callback: passing control to the next middleware &gt;");
    next();
  },
  (req, res, next) =&gt; {
    console.log("Second callback: passing control to the next middleware &gt;");
    next();
  },
  (req, res) =&gt; {
    res.send("Request handled with multiple middleware functions!");
  },
);
</code></pre>
<p>The example above uses multiple middleware functions to handle GET requests to the <code>/multiple/middleware</code> path.</p>
<h4 id="heading-express-route-with-an-array-of-middleware-functions">Express route with an array of middleware functions</h4>
<pre><code class="language-javascript">const arrayOfCallbacks = [
  function callback1(req, res, next) {
    console.log("First callback: passing control to the next middleware &gt;");
    next();
  },
  function callback2(req, res, next) {
    console.log("Second callback: passing control to the next middleware &gt;");
    next();
  },
  function callback3(req, res) {
    res.send("Request handled with an array of middleware functions!");
  },
];

app.get("/array/middleware", arrayOfCallbacks);
</code></pre>
<p>The example above uses an array of callback functions to handle GET requests to the <code>GET /array/middleware</code> endpoint.</p>
<h4 id="heading-express-route-with-a-combination-of-an-array-of-middleware-functions-and-individual-callbacks">Express route with a combination of an array of middleware functions and individual callbacks</h4>
<pre><code class="language-javascript">const arrayOfCallbacks = [
  function callback1(req, res, next) {
    console.log("First callback: passing control to the next middleware &gt;");
    next();
  },
  function callback2(req, res, next) {
    console.log("Second callback: passing control to the next middleware &gt;");
    next();
  },
];

app.get(
  "/mix/middleware",
  arrayOfCallbacks,
  (req, res, next) =&gt; {
    console.log("Third callback: passing control to the next middleware &gt;");
    next();
  },
  (req, res, next) =&gt; {
    console.log("Fourth callback: passing control to the next middleware &gt;");
    next();
  },
  (req, res) =&gt; {
    res.send(
      "Request handled with a combination of an array of middleware functions and independent callback arguments!",
    );
  },
);
</code></pre>
<p>The example above uses both an array of callbacks and individual function arguments to handle GET requests to the <code>/mix/middleware</code> path.</p>
<h3 id="heading-important-things-to-know-about-the-next-parameter">Important Things to Know About the <code>next</code> Parameter</h3>
<ul>
<li><p><code>next()</code> passes control to the next middleware function in the stack.</p>
</li>
<li><p><code>next("route")</code> skips the remaining handlers for the current route and continues looking for a matching route. Matching considers both the request method and path. It is only effective within middleware functions defined for <code>app.METHOD()</code> or <code>router.METHOD()</code>.</p>
</li>
<li><p><code>next(new Error(value))</code> passes control to the next error-handling middleware.</p>
</li>
<li><p>If the currently running middleware does not end the request-response cycle, include a <code>next</code> parameter and invoke it within the callback to pass control to the next middleware. Otherwise, the client's request will remain pending.</p>
</li>
</ul>
<h3 id="heading-categories-of-middleware-in-expressjs">Categories of Middleware in Express.js</h3>
<p>Express middleware can be classified into five primary categories:</p>
<ul>
<li><p>Application-level</p>
</li>
<li><p>Router-level</p>
</li>
<li><p>Error-handling</p>
</li>
<li><p>Built-in</p>
</li>
<li><p>Third-party</p>
</li>
</ul>
<p>These categories describe where middleware is mounted, how it behaves, or its source.</p>
<h4 id="heading-application-level-middleware">Application-level middleware</h4>
<p>This type of middleware is attached to the Express application instance (<code>app</code>).</p>
<p><strong>Example:</strong></p>
<pre><code class="language-javascript">import express from "express";
const app = express();

app.get("/profile", (req, res, next) =&gt; {
  console.log("Hi, there!");
  next();
});
</code></pre>
<h4 id="heading-router-level-middleware">Router-level middleware</h4>
<p>This middleware is attached to an Express Router instance (<code>router</code>). It operates similarly to application-level middleware but is mounted on a router instead of the application.</p>
<p><strong>Example:</strong></p>
<pre><code class="language-javascript">import express from "express";
const router = express.Router();

router.get("/profile", (req, res, next) =&gt; {
  console.log("Hi, there!");
  next();
});
</code></pre>
<h4 id="heading-error-handling-middleware">Error-handling middleware</h4>
<p>This middleware handles errors during request processing and is identified by its four-parameter signature.</p>
<pre><code class="language-javascript">import express from "express";
const app = express();

app.use((err, req, res, next) =&gt; {
  console.error(err);
  res.status(500).send("Error 500: Encountered an unexpected error");
});
</code></pre>
<p><strong>Note:</strong></p>
<ul>
<li><p>All four parameters must be present, even if some are unused. Otherwise, Express won't recognize the function as error-handling middleware. Express uses the number of declared parameters, not their names, to identify such middleware.</p>
</li>
<li><p>Define error-handling middleware after the routes and middleware whose errors it should handle. This placement ensures it processes errors passed from preceding middleware functions.</p>
</li>
</ul>
<h4 id="heading-built-in-middleware">Built-in middleware</h4>
<p>These middleware functions are included with Express and available by default, without requiring additional package installations.</p>
<p><strong>Examples:</strong></p>
<pre><code class="language-javascript">import express from "express";

express.static("public");
express.json();
express.urlencoded();
</code></pre>
<h4 id="heading-third-party-middleware">Third-party middleware</h4>
<p>These middleware functions are provided by external packages developed and shared by the broader Express community. Examples include cors, morgan, and helmet.</p>
<pre><code class="language-typescript">import express from "express";
import cors from "cors";

const app = express();
app.use(cors());
</code></pre>
<h4 id="heading-note-middleware-categories-in-express-are-not-mutually-exclusive">Note: Middleware categories in Express are not mutually exclusive</h4>
<p><strong>Example 1:</strong></p>
<pre><code class="language-javascript">import express from "express";

const app = express();
app.use(express.json());
</code></pre>
<p>The <code>express.json()</code> middleware in the snippet above is both:</p>
<ul>
<li><p>Application-level, because it is attached to the <code>app</code> instance</p>
</li>
<li><p>Built-in, because Express provides it</p>
</li>
</ul>
<p><strong>Example 2:</strong></p>
<pre><code class="language-javascript">import express from "express";
import cors from "cors";

const router = express.Router();
router.use(cors());
</code></pre>
<p>The <code>cors()</code> middleware in the snippet above is both:</p>
<ul>
<li><p>Router-level, because it is attached to the <code>router</code> instance</p>
</li>
<li><p>Third-party, because a package outside of Express provided it</p>
</li>
</ul>
<p>Are you asking what the <code>express.Router()</code> method in the example above is? Let's discuss it.</p>
<h2 id="heading-what-is-the-expressrouter-method">What Is the <code>express.Router()</code> Method?</h2>
<p>The <code>express.Router()</code> method creates a router object that groups related routes and middleware. You can attach this router to an Express application or another router using <code>app.use()</code> or <code>router.use()</code>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/61672d1653401f641ba159b4/1ae7a155-57df-42dd-ae99-940c92f3f1f3.jpg" alt="Why is Express Router a mini-app?" style="display: block;" width="1920" height="1920" loading="lazy">

<p>As illustrated in the image above, a router is often called a mini-app because it provides a complete middleware and routing system. It helps organize applications by allowing you to define related routes in one place and mount them onto the main Express application. For instance, suppose your Express application needs to handle the following categories of routes and middleware:</p>
<ul>
<li><p><strong>Index:</strong> For index-related routes and middleware.</p>
</li>
<li><p><strong>Books:</strong> For book-related routes and middleware.</p>
</li>
<li><p><strong>Videos:</strong> For video-related routes and middleware.</p>
</li>
</ul>
<p>In this situation, you can use the <code>express.Router()</code> method to group related routes and middleware. This keeps things organized and makes each group easier to manage and reuse.</p>
<p>While you can create all router and app instances in one file, developers usually place routers in separate files for better organization and maintainability. Let's follow this approach by creating separate files for each route and middleware category.</p>
<h3 id="heading-create-a-directory-for-the-routers">Create a Directory for the Routers</h3>
<p>Create a <code>routes</code> directory at your project's root to store all the app's routers.</p>
<pre><code class="language-console">mkdir routes
</code></pre>
<p><strong>Note:</strong> You can name this folder whatever you like, but <code>routes</code> is a common name since it holds the files that define your app's routes (URL endpoints). The <code>express.Router()</code> method is just a tool that Express provides for managing those routes.</p>
<h3 id="heading-create-the-route-files">Create the Route Files</h3>
<p>A route file is a module where you define related routes and export an Express router object. Each file usually represents a resource or feature, such as users, books, or authentication.</p>
<p>Create the route files in the <code>routes</code> directory.</p>
<pre><code class="language-console">touch routes/index.js routes/books.js routes/videos.js
</code></pre>
<h3 id="heading-create-a-mini-app-for-the-book-related-routes-and-middleware">Create a Mini-App for the Book-Related Routes and Middleware</h3>
<p>Open the <code>books.js</code> file and use an <code>express.Router()</code> instance to group all the book-related routes and middleware.</p>
<p><code>routes/books.js</code></p>
<pre><code class="language-javascript">// Import the Router function from Express
import { Router } from "express";

// Create a new Express router instance
const bookRouter = Router();

// Define middleware specific to this router instance
bookRouter.use((req, res, next) =&gt; {
  console.log("Book route accessed at: ", Date.now());
  next();
});

// Define routes specific to this router instance:

bookRouter.get("/", (req, res) =&gt; {
  res.send("&lt;h1&gt;List of All Books&lt;/h1&gt;");
});

bookRouter.get("/:id", (req, res) =&gt; {
  res.type("text/plain").send(`Details for book ${req.params.id}`);
});

bookRouter.get("/:id/draft", (req, res) =&gt; {
  // Escape the ID before inserting it into HTML text
  const bookId = req.params.id
    .replaceAll("&amp;", "&amp;amp;")
    .replaceAll("&lt;", "&amp;lt;")
    .replaceAll("&gt;", "&amp;gt;");
  res.send(`&lt;h1&gt;New Draft for Book ${bookId}&lt;/h1&gt;`);
});

export { bookRouter };
</code></pre>
<p>Here's what the code above does:</p>
<ul>
<li><p>Creates a <code>bookRouter</code> instance to access Express APIs, such as <code>.get()</code>, <code>.post()</code>, <code>.use()</code>, and <code>.route()</code>.</p>
</li>
<li><p>Uses Express's <code>router.use()</code> method to mount middleware onto the <code>bookRouter</code> instance.</p>
</li>
<li><p>Uses Express's <code>router.get()</code> method to define how the server handles HTTP GET requests.</p>
</li>
<li><p>Uses Express's <code>res.send()</code> method to send an HTTP response and automatically set the appropriate headers based on the data type provided. The <code>/:id</code> handler explicitly sets the response type to plain text, while the <code>/:id/draft</code> handler escapes the ID before inserting it into HTML so it is displayed as text.</p>
</li>
<li><p>Uses the <code>export</code> statement to make the router object available for import wherever it is needed in the application.</p>
</li>
</ul>
<h3 id="heading-time-to-practice-with-routers">Time to Practice with Routers</h3>
<p>This is your moment to try out what you've learned about Express routers.</p>
<p>For this exercise, create mini-apps for the project's index and video-related routes and middleware. Export them as <code>indexRouter</code> from <code>routes/index.js</code> and <code>videoRouter</code> from <code>routes/videos.js</code> to match the imports in the next section.</p>
<p>Take a moment to try this on your own before moving on. If you need help, review the <code>books.js</code> file. Practicing will help you understand better.</p>
<p>After you finish the exercise, move on to setting up the main Express app.</p>
<h3 id="heading-update-the-main-express-application">Update the Main Express Application</h3>
<p>Open your project's <code>server.js</code> file and attach the routers to the main Express application.</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">// Add the Express module
import express from "express";

// Import the routers from their separate files
import { indexRouter } from "./routes/index.js";
import { bookRouter } from "./routes/books.js";
import { videoRouter } from "./routes/videos.js";

// Create a new Express application instance
const app = express();

// Specify the host and port to receive requests
const host = "localhost";
const port = 3000;

// Mount the routers to specific paths:

// Mount indexRouter at /
app.use("/", indexRouter);

// Mount bookRouter at /books and its subpaths
app.use("/books", bookRouter);

// Mount videoRouter at /videos and its subpaths
app.use("/videos", videoRouter);

// Run the server on the specified port and host
app.listen(port, host, () =&gt; {
  console.log(`Server running live at http://${host}:
${port}!`);
});
</code></pre>
<p>Here's what the code above does:</p>
<ul>
<li><p>Creates an Express application instance to access Express APIs, such as routers and middleware, which simplifies HTTP request handling in Node.js.</p>
</li>
<li><p>Uses Express's <code>app.use()</code> method to add the mini-apps to the main Express application.</p>
</li>
<li><p>Uses Express's <code>app.listen()</code> method to start the Node.js HTTP server on a specific port and execute a callback when the server begins listening for client requests.</p>
</li>
</ul>
<p><strong>Note:</strong> The <code>app.use()</code> method's path serves as the router's base path or mount path. Routes defined in the router are matched relative to this mount path. For example:</p>
<ul>
<li><p><code>bookRouter</code>'s <code>/</code> route matches requests to <code>/books</code>.</p>
</li>
<li><p><code>bookRouter</code>'s <code>/:id</code> route matches requests to <code>/books/:id</code>.</p>
</li>
<li><p><code>bookRouter</code>'s <code>/:id/draft</code> route matches requests to <code>/books/:id/draft</code>.</p>
</li>
</ul>
<h3 id="heading-run-your-expressjs-application">Run your Express.js Application</h3>
<p>Once you've set up the routers, run your app by starting the server file with Node.js.</p>
<pre><code class="language-console">node --watch server.js
</code></pre>
<p>Then, check your app running live at the specified endpoints. For example, <code>http://localhost:3000/books</code>.</p>
<p><strong>Tip:</strong> Stop the running process using <code>Ctrl + C</code> on Windows, macOS, or Linux.</p>
<h3 id="heading-important-things-to-know-about-express-routers">Important Things to Know About Express Routers</h3>
<p>Here are some important things to remember when using Express routers.</p>
<h4 id="heading-routers-do-not-inherit-parent-route-parameters-by-default">Routers do not inherit parent route parameters by default</h4>
<p>By default, Express doesn't pass parameters from a router's mount path to routes inside that router.</p>
<p><strong>Example:</strong></p>
<pre><code class="language-javascript">// Add the Express module
import express from "express";

// Create a new Express application instance
const app = express();

// Create a new Express router instance
const bookRouter = express.Router();

// Define a sub-route
bookRouter.get("/books/:bookId", (req, res) =&gt; {
  const topic = req.params.topic; // undefined by default
  const bookId = req.params.bookId;
  res.json({ topic, bookId });
});

// Define a parent route
app.use("/codesweetly/:topic", bookRouter);

// Run the server on the specified port and host
const server = app.listen(3000, "127.0.0.1", () =&gt; {
  const { address, port } = server.address();
  console.log(`Server running live at http://${address}:
${port}!`);
});
</code></pre>
<p>If you run the web server in the example above and enter the following URL in the browser:</p>
<pre><code class="language-txt">http://127.0.0.1:3000/codesweetly/CSS/books/91827
</code></pre>
<p>The <code>req.params.topic</code> parameter will be <code>undefined</code> because sub-routes can't access the parent route's path parameter by default. So, the server will only send a <code>{"bookId":"91827"}</code> response to the client.</p>
<p>To let a child route access its parent's path parameter, set <code>mergeParams</code> to <code>true</code> when you create the router.</p>
<p><strong>Example:</strong></p>
<pre><code class="language-javascript">// Add the Express module
import express from "express";

// Create a new Express application instance
const app = express();

// Create a new Express router instance
const bookRouter = express.Router({ mergeParams: true });

// Define a sub-route
bookRouter.get("/books/:bookId", (req, res) =&gt; {
  const topic = req.params.topic; // "CSS" for the URL below
  const bookId = req.params.bookId;
  res.json({ topic, bookId });
});

// Define a parent route
app.use("/codesweetly/:topic", bookRouter);

// Run the server on the specified port and host
const server = app.listen(3000, "127.0.0.1", () =&gt; {
  const { address, port } = server.address();
  console.log(`Server running live at http://${address}:
${port}!`);
});
</code></pre>
<p>If you run the web server in the example above and enter the following URL in your browser:</p>
<pre><code class="language-txt">http://127.0.0.1:3000/codesweetly/CSS/books/91827
</code></pre>
<p>The <code>req.params.topic</code> parameter will be <code>CSS</code> because <code>mergeParams: true</code> lets the sub-route access the parent's path parameter. So, the server will send a <code>{"topic":"CSS","bookId":"91827"}</code> response to the client.</p>
<p><strong>Tip:</strong></p>
<ul>
<li><p>The line <code>const { address, port } = server.address()</code> uses <a href="https://codesweetly.com/destructuring-object">object destructuring</a> to get the <code>address</code> and <code>port</code> values from the <code>server.address()</code> object.</p>
</li>
<li><p>The <code>app.listen()</code> method returns a native Node.js <code>http.Server</code> instance, allowing access to underlying server APIs such as <code>.address()</code>, <code>.on()</code>, and <code>.maxHeadersCount</code>.</p>
</li>
<li><p><code>127.0.0.1</code> is an IPv4 loopback address. <code>localhost</code> may resolve to <code>127.0.0.1</code> or the IPv6 loopback address <code>::1</code>. Use <code>http://127.0.0.1:3000</code> for these examples because the server explicitly listens on that IPv4 address.</p>
</li>
</ul>
<h4 id="heading-routers-can-be-mounted-on-other-routers">Routers can be mounted on other routers</h4>
<p>You can attach one Express router to another.</p>
<p><strong>Example:</strong></p>
<pre><code class="language-javascript">// Add the Express module
import express from "express";

// Create a new Express application instance
const app = express();

// Create two Express router instances
const htmlRouter = express.Router();
const bookRouter = express.Router();

// Define a sub-route
bookRouter.get("/:bookId", (req, res) =&gt; {
  res
    .type("text/plain")
    .send(`Details for the HTML book with ID ${req.params.bookId}`);
});

// Mount bookRouter on htmlRouter's /books path
htmlRouter.use("/books", bookRouter);

// Mount htmlRouter at /html and its subpaths
app.use("/html", htmlRouter);

// Run the server on the specified port and host
const server = app.listen(3000, "127.0.0.1", () =&gt; {
  const { address, port } = server.address();
  console.log(`Server running live at http://${address}:
${port}!`);
});
</code></pre>
<p>The <code>bookRouter</code>'s <code>GET /:bookId</code> route matches requests to <code>GET /html/books/:bookId</code> because, in this example, the book router is attached to <code>htmlRouter</code>.</p>
<p>Therefore, if you run the web server in the example above and enter the following URL in the browser:</p>
<pre><code class="language-txt">http://127.0.0.1:3000/html/books/91827
</code></pre>
<p>The server will send a "Details for the HTML book with ID 91827" response to the client.</p>
<p>Now that you know what a router is, let's discuss how to use views to define the content and structure of the webpage your Express.js app returns to users.</p>
<h2 id="heading-what-is-a-view-in-expressjs">What Is a View in Express.js?</h2>
<p>A view is a template or document that defines the content and structure of a webpage returned to users by an Express.js application. It can be a static HTML file or a dynamic template rendered into HTML at <a href="https://codesweetly.com/web-tech-terms-r/#runtime">runtime</a> by a template engine.</p>
<p>In this guide, we'll work with two types of views:</p>
<ul>
<li><p>Static views</p>
</li>
<li><p>Dynamic views</p>
</li>
</ul>
<h3 id="heading-what-are-static-views-in-expressjs">What Are Static Views in Express.js?</h3>
<p>Static views contain the final HTML that the server sends to the browser as-is. For example, let's configure your Express.js application to serve four static views.</p>
<h4 id="heading-create-static-views">Create static views</h4>
<p>Create <code>index.html</code>, <code>about.html</code>, <code>contact.html</code>, and <code>404.html</code> files in your project's root directory.</p>
<pre><code class="language-console">touch index.html about.html contact.html 404.html
</code></pre>
<p>Open each view and add the following HTML content:</p>
<h5 id="heading-indexhtml-homepage">index.html (homepage)</h5>
<pre><code class="language-html">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="UTF-8" /&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
    &lt;title&gt;Static Views in Express.js | CodeSweetly Tutorial&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Welcome to the Static View Guide&lt;/h1&gt;
    &lt;p&gt;Site's pages:&lt;/p&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href="/about"&gt;About&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href="/contact"&gt;Contact&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h5 id="heading-abouthtml-about-page">about.html (about page)</h5>
<pre><code class="language-html">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="UTF-8" /&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
    &lt;title&gt;About Us | Static Views in Express.js&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;About Us&lt;/h1&gt;
    &lt;p&gt;
      Lorem ipsum dolor sit amet consectetur adipisicing elit. Libero soluta
      voluptas reprehenderit minus veniam! Corrupti a esse quidem nostrum harum,
      explicabo tempore tempora aut, sint et voluptatem magni ea vel?
    &lt;/p&gt;
    &lt;div&gt;&lt;a href="/"&gt;Return to the home page&lt;/a&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h5 id="heading-contacthtml-contact-page">contact.html (contact page)</h5>
<pre><code class="language-html">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="UTF-8" /&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
    &lt;title&gt;Contact | Static Views in Express.js&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Contact Us&lt;/h1&gt;
    &lt;ul&gt;
      &lt;li&gt;&lt;a href="https://codesweetly.com"&gt;Website&lt;/a&gt;&lt;/li&gt;
      &lt;li&gt;&lt;a href="https://x.com/oluwatobiss"&gt;X (Twitter)&lt;/a&gt;&lt;/li&gt;
    &lt;/ul&gt;
    &lt;div&gt;&lt;a href="/"&gt;Return to the home page&lt;/a&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h5 id="heading-404html-error-page">404.html (error page)</h5>
<pre><code class="language-html">&lt;!doctype html&gt;
&lt;html lang="en"&gt;
  &lt;head&gt;
    &lt;meta charset="UTF-8" /&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0" /&gt;
    &lt;title&gt;404 - Page not found | Static Views in Express.js&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;h1&gt;Page not found&lt;/h1&gt;
    &lt;div&gt;Sorry, we couldn't find that page&lt;/div&gt;
    &lt;div&gt;&lt;a href="/"&gt;Go back to the home page&lt;/a&gt;&lt;/div&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Next, configure your project to handle browser connections.</p>
<h4 id="heading-configure-the-projects-web-server-to-serve-static-views">Configure the project's web server to serve static views</h4>
<p>Open the project's <code>server.js</code> module and configure the web server to serve the appropriate static HTML view in response to requests.</p>
<pre><code class="language-javascript">// Add the required modules
import express from "express";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

// Create a new Express application instance
const app = express();

// Specify the hostname and port to receive requests
const host = "localhost";
const port = 3000;

// Get the directory name of the current file's path
const __dirname = dirname(fileURLToPath(import.meta.url));

// Use the index.html static view as a response to 'GET /' requests
app.get("/", (req, res) =&gt; res.sendFile(join(__dirname, "index.html")));

// Use the about.html static view as a response to 'GET /about' requests
app.get("/about", (req, res) =&gt; {
  res.sendFile(join(__dirname, "about.html"));
});

// Use the contact.html static view as a response to 'GET /contact' requests
app.get("/contact", (req, res) =&gt; {
  res.sendFile(join(__dirname, "contact.html"));
});

// Use the 404.html static view as a response to unmatched requests
app.use((req, res) =&gt; {
  res.status(404).sendFile(join(__dirname, "404.html"));
});

// Run the server on the specified port and hostname
app.listen(port, host, () =&gt; {
  console.log(`Server running live at http://${host}:
${port}`);
});
</code></pre>
<p>Here are the main things the snippet above does:</p>
<ul>
<li><p>Create an Express application instance to access Express APIs, such as routers and middleware, which simplify HTTP request handling in Node.js.</p>
</li>
<li><p>Get the directory name of the current file's path.</p>
<ul>
<li><p><code>dirname()</code> returns a path's directory name.</p>
</li>
<li><p><code>fileURLToPath()</code> converts a URL to a valid path string.</p>
</li>
<li><p><code>import.meta.url</code> returns the absolute URL of the current file.</p>
</li>
</ul>
</li>
<li><p>Create routes to receive and respond to clients' requests.</p>
<ul>
<li><p><code>app</code> is an Express application instance.</p>
</li>
<li><p>The <code>app.get()</code> method defines how the server handles HTTP GET requests to the specified path (the method's first argument).</p>
</li>
<li><p>The <code>res.sendFile()</code> method sends a file from the server to the client.</p>
</li>
<li><p><code>join()</code> joins multiple path segments into a single, normalized path string using the current operating system’s path separator.</p>
</li>
<li><p>The <code>app.use()</code> method lets you set up handler functions that Express runs for all HTTP request methods and paths. If you specify a path argument, <code>app.use()</code> treats it as a prefix for matching routes. For example, <code>/book</code> matches <code>/book</code>, <code>/book/dashboard</code>, and <code>/book/dashboard/author/202605</code>.</p>
</li>
<li><p><code>res.status(404)</code> sets the HTTP status code to 404 for a request that reaches this final handler without receiving a response.</p>
</li>
</ul>
</li>
<li><p>Use Express's <code>app.listen()</code> method to start the Node.js HTTP server on a specific port and execute a callback when the server begins listening for client requests.</p>
</li>
</ul>
<h4 id="heading-run-your-expressjs-application">Run your Express.js application</h4>
<p>Once you've set up the server, run it with Node.js.</p>
<pre><code class="language-console">node --watch server.js
</code></pre>
<p>Afterward, check your app running live at <code>http://localhost:3000</code>.</p>
<p><strong>Tip:</strong> Stop the running process using <code>Ctrl + C</code> on Windows, macOS, or Linux.</p>
<p>To keep things organized, put all your static views in a <code>public</code> directory. This is a common practice.</p>
<h4 id="heading-create-a-directory-for-static-views">Create a directory for static views</h4>
<p>Create a <code>public</code> directory at your project's root to store all static views.</p>
<pre><code class="language-console">mkdir public
</code></pre>
<p><strong>Note:</strong> You can name this folder whatever you like, but <code>public</code> is a common choice to indicate that its files (HTML, CSS, client-side JavaScript, images) are intended to be served to clients. The folder's name alone does not make its contents accessible. The server must be configured to serve them. Don't put sensitive information in it.</p>
<h4 id="heading-move-all-static-views-into-the-public-folder">Move all static views into the <code>public</code> folder</h4>
<pre><code class="language-console">mv index.html about.html contact.html 404.html public/
</code></pre>
<h4 id="heading-update-the-server-to-retrieve-static-views-from-the-public-folder">Update the server to retrieve static views from the <code>public</code> folder</h4>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import express from "express";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const app = express();
const host = "localhost";
const port = 3000;
const __dirname = dirname(fileURLToPath(import.meta.url));

// Serve static assets (HTML, CSS, images) from the 'public' folder
app.use(express.static(join(__dirname, "public")));

// Use the index.html static view as a response to 'GET /' requests
app.get("/", (req, res) =&gt; {
  res.sendFile(join(__dirname, "/public/index.html"));
});

// Use the about.html static view as a response to 'GET /about' requests
app.get("/about", (req, res) =&gt; {
  res.sendFile(join(__dirname, "/public/about.html"));
});

// Use the contact.html static view as a response to 'GET /contact' requests
app.get("/contact", (req, res) =&gt; {
  res.sendFile(join(__dirname, "/public/contact.html"));
});

// Use the 404.html static view as a response to unmatched requests
app.use((req, res) =&gt; {
  res.status(404).sendFile(join(__dirname, "/public/404.html"));
});

// Run the server on the specified port and hostname:
app.listen(port, host, () =&gt; {
  console.log(`Server running live at http://${host}:
${port}`);
});
</code></pre>
<p><strong>Note</strong> The <code>app.use(express.static(join(__dirname, 'public')))</code> line tells Express to check the public folder first for static asset requests. If it finds the file there, it immediately serves it to the browser and stops the request-response cycle.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p>If a user requests <code>localhost:3000/about.html</code>, <code>express.static</code> checks the <code>public</code> folder for the <code>about.html</code> file. If found, Express automatically sends it without running the route handlers that follow the static middleware.</p>
</li>
<li><p>If a user asks for <code>localhost:3000/about</code>, <code>express.static</code> checks the <code>public</code> folder for an <code>about</code> file (no extension). If it finds an <code>about</code> directory instead, it redirects to <code>/about/</code>, where it looks for <code>index.html</code> by default. With the files created in this guide, neither an <code>about</code> file nor an <code>about</code> directory exists, so Express uses the <code>GET /about</code> custom route to handle the request.</p>
</li>
</ul>
<p>Let's now discuss dynamic views.</p>
<h3 id="heading-what-are-dynamic-views-in-expressjs">What Are Dynamic Views in Express.js?</h3>
<p>Dynamic views contain placeholders that template engines, such as EJS, replace with data at runtime.</p>
<p>Express.js supports template engines such as EJS, Pug, and Handlebars. Let's use EJS as an example to discuss how dynamic views work.</p>
<h4 id="heading-what-is-ejs">What is EJS?</h4>
<p>EJS (<a href="https://ejs.co">Embedded JavaScript templating</a>) is a templating language that lets you create dynamic HTML views by embedding JavaScript code within HTML templates using template tags.</p>
<p>When the server renders a template, the EJS engine executes the embedded JavaScript and generates the final HTML sent to the client.</p>
<p>For instance, consider the following code. Install EJS with <code>npm install ejs</code> before running this example:</p>
<pre><code class="language-javascript">// Add the Express and EJS modules
import express from "express";
import ejs from "ejs";

// Create a new Express application instance
const app = express();

// Specify the host and port to receive requests
const host = "localhost";
const port = 8000;

// Define the data object
const friendsArray = ["Sarah", "Abraham", "Mary"];
const replacementObject = { friends: friendsArray };

// Use backticks to define a template string with embedded JavaScript
const templateString = `
  &lt;h1&gt;Hello, &lt;%= friends.join(", "); %&gt;!&lt;/h1&gt;
  &lt;p&gt;Welcome to CodeSweetly.&lt;/p&gt;
`;

// Compile and render the template string to HTML (the rendered view)
const html = ejs.render(templateString, replacementObject);

// Use the dynamic view as a response to 'GET /' requests
app.get("/", (req, res) =&gt; res.send(html));

// Run the server on the specified port and hostname
app.listen(port, host, () =&gt; {
  console.log(`Server running live at http://${host}:
${port}!`);
});
</code></pre>
<p>The above snippet tells Express to send the rendered view to the client when users request the <code>/</code> path.</p>
<p>At runtime, EJS evaluates <code>friends.join(", ")</code> using the array passed as <code>friends</code> and inserts the result, <code>Sarah, Abraham, Mary</code>, into the HTML. Here, rendering happens once when the script starts. Each request receives that same rendered HTML.</p>
<h4 id="heading-what-are-ejs-template-tags">What are EJS template tags?</h4>
<p>EJS template tags are special tags written using the <code>&lt;% ... %&gt;</code> syntax. They allow JavaScript code and values to be embedded into EJS view templates.</p>
<p>When EJS renders the template, scriptlet tags execute JavaScript, output tags insert values, and comment tags are ignored.</p>
<p>For example, the <code>&lt;%= %&gt;</code> tags below allow you to embed a JavaScript <code>friend</code> variable into the view template.</p>
<pre><code class="language-ejs">&lt;h1&gt;About &lt;%= friend %&gt;, my special pal&lt;/h1&gt;
</code></pre>
<p><strong>Note:</strong> Output tags such as <code>&lt;%= %&gt;</code> must contain a valid JavaScript expression. Scriptlet tags can contain JavaScript statements and parts of control-flow structures, while comment tags contain comments.</p>
<p><strong>Example:</strong></p>
<ul>
<li><p><code>&lt;%= &lt;p&gt;I love CodeSweetly&lt;/p&gt; %&gt;</code> will throw an error because <code>&lt;p&gt;I love CodeSweetly&lt;/p&gt;</code> is HTML, not JavaScript.</p>
</li>
<li><p><code>&lt;%= "&lt;p&gt;I love CodeSweetly&lt;/p&gt;" %&gt;</code> is valid because <code>"&lt;p&gt;I love CodeSweetly&lt;/p&gt;"</code> is embedded as a JavaScript string data type.</p>
</li>
</ul>
<h4 id="heading-types-of-ejs-template-tags">Types of EJS template tags</h4>
<p>The nine EJS tag forms covered here are as follows:</p>
<p><strong>Tip:</strong> Wrap JavaScript code in EJS tags to distinguish it from the surrounding template content. A single pair of tags can contain multiple lines of JavaScript.</p>
<h5 id="heading-closing-tag-gt">Closing tag (<code>%&gt;</code>)</h5>
<p>Use the closing tag to end an EJS tag. It has no special behavior on its own.</p>
<h5 id="heading-scriptlet-tag-lt">Scriptlet tag (<code>&lt;%</code>)</h5>
<p>Use the scriptlet tag to run JavaScript code without outputting anything into the generated HTML. This tag is commonly used for control flow, such as <code>if</code>, <code>for</code>, and <code>forEach</code> logic.</p>
<pre><code class="language-ejs">&lt;ul&gt;
  &lt;% friends.forEach(function () { %&gt;
  &lt;li&gt;My friend&lt;/li&gt;
  &lt;% }) %&gt;
&lt;/ul&gt;
</code></pre>
<p>The snippet above wraps <code>&lt;% %&gt;</code> around the control-flow syntax to indicate to EJS that the JavaScript code is only for logic and should not be rendered to the generated HTML.</p>
<h5 id="heading-escaped-output-tag-lt">Escaped output tag (<code>&lt;%=</code>)</h5>
<p>Use the escaped output tag to evaluate JavaScript expressions and output the result into the generated HTML while escaping HTML characters. This tag helps prevent <a href="https://www.utep.edu/information-resources/iso/security-awareness/technical-security-resources/what-is-html-injection.html">HTML injection</a>.</p>
<pre><code class="language-ejs">&lt;%= 100 + 200 %&gt;
</code></pre>
<p>The above snippet wraps <code>&lt;%= %&gt;</code> around the arithmetic expression to tell EJS to render the code's value into the generated HTML.</p>
<p><strong>Note:</strong> If the expression evaluates to a string containing HTML, <code>&lt;%= %&gt;</code> escapes the HTML syntax so the browser displays it as text. For example, <code>&lt;%= "&lt;h1&gt;About CodeSweetly&lt;/h1&gt;" %&gt;</code> will render <code>&lt;h1&gt;About CodeSweetly&lt;/h1&gt;</code> as text, not an actual <code>&lt;h1&gt;</code> element.</p>
<h5 id="heading-unescaped-output-tag-lt">Unescaped output tag (<code>&lt;%-</code>)</h5>
<p>Use the unescaped tag to evaluate JavaScript expressions and output the result into the generated HTML without escaping HTML characters.</p>
<pre><code class="language-ejs">&lt;%- "&lt;h1&gt;About CodeSweetly&lt;/h1&gt;" %&gt;
</code></pre>
<p>The snippet above wraps <code>&lt;%- %&gt;</code> around a string containing an <code>&lt;h1&gt;</code> element so the browser renders it as HTML. Use unescaped output only for trusted HTML.</p>
<h5 id="heading-literal-opening-tag-lt">Literal opening tag (<code>&lt;%%</code>)</h5>
<p>Use the literal tag to output a literal <code>&lt;%</code> sequence instead of treating it as an EJS tag. This is useful when you want to show EJS syntax in the generated output.</p>
<pre><code class="language-ejs">&lt;%% "&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; &lt;em&gt;Oluwatobi&lt;/em&gt;&lt;/p&gt;" %&gt;
</code></pre>
<p>The snippet above outputs a literal <code>&lt;%</code> followed by the remaining text, without evaluating it as JavaScript. The generated HTML source is:</p>
<pre><code class="language-plaintext">&lt;% "
&lt;p&gt;&lt;strong&gt;Name:&lt;/strong&gt; &lt;em&gt;Oluwatobi&lt;/em&gt;&lt;/p&gt;
" %&gt;
</code></pre>
<p>The HTML tags remain unescaped, so this shows the generated source, not how the browser displays the page.</p>
<h5 id="heading-newline-trimmed-ending-tag-gt">Newline-trimmed ending tag (<code>-%&gt;</code>)</h5>
<p>Use the newline-trimmed ending tag to remove the newline immediately after the closing tag.</p>
<pre><code class="language-ejs">&lt;ul&gt;
  &lt;% friends.forEach(function (friend) { %&gt;
  &lt;li&gt;&lt;%= friend -%&gt;&lt;/li&gt;
  &lt;% }) %&gt;
&lt;/ul&gt;
</code></pre>
<p>The snippet above wraps <code>&lt;%= -%&gt;</code> around the <code>friend</code> variable to tell EJS to trim any newline following the closing EJS tag.</p>
<p><strong>Tip:</strong> The newline-trimmed ending tag is also called the newline slurp tag.</p>
<h5 id="heading-whitespace-slurp-opening-tag-lt">Whitespace slurp opening tag (<code>&lt;%_</code>)</h5>
<p>Use the whitespace slurping tag to remove spaces and tabs immediately before the opening EJS tag on the same line.</p>
<pre><code class="language-ejs">&lt;ul&gt;
  &lt;%_ friends.forEach(function (friend) { %&gt;
  &lt;li&gt;&lt;%= friend %&gt;&lt;/li&gt;
  &lt;%_ }) %&gt;
&lt;/ul&gt;
</code></pre>
<p>The snippet above wraps <code>&lt;%_ %&gt;</code> around the control-flow syntax to tell EJS to trim the indentation before the template tags.</p>
<h5 id="heading-whitespace-slurp-closing-tag-gt">Whitespace slurp closing tag (<code>_%&gt;</code>)</h5>
<p>Use the whitespace slurping ending tag to remove spaces and tabs immediately after the closing tag, followed by one newline if present.</p>
<pre><code class="language-ejs">&lt;ul&gt;
  &lt;% friends.forEach(function (friend) { _%&gt;
  &lt;li&gt;&lt;%= friend %&gt;&lt;/li&gt;
  &lt;% }) _%&gt;
&lt;/ul&gt;
</code></pre>
<p>The snippet above wraps <code>&lt;% _%&gt;</code> around the control-flow syntax to tell EJS to trim the newline after each closing tag. The indentation on the following line remains.</p>
<h5 id="heading-comment-tag-lt">Comment tag (<code>&lt;%#</code>)</h5>
<p>Use the comment tag to add EJS comments that are ignored during rendering and do not appear in the generated HTML.</p>
<pre><code class="language-ejs">&lt;ul&gt;
  &lt;%# Loop through the friends array %&gt;
  &lt;% friends.forEach(function (friend) { _%&gt;
  &lt;li&gt;&lt;%= friend %&gt;&lt;/li&gt;
  &lt;% }) _%&gt;
&lt;/ul&gt;
</code></pre>
<p>The snippet above wraps the comment in <code>&lt;%# %&gt;</code>.</p>
<p><strong>Tip:</strong> EJS allows you to combine some tags. For example, the following combinations are possible:</p>
<ul>
<li><p><code>&lt;%_ _%&gt;</code>: Combine the whitespace slurping scriptlet and ending tag to remove adjacent spaces and tabs on the same line, plus one following newline if present.</p>
</li>
<li><p><code>&lt;% -%&gt;</code>: Combine the control-flow with the newline slurp.</p>
</li>
<li><p><code>&lt;%= -%&gt;</code>: Combine the escaped tag with the newline slurp.</p>
</li>
</ul>
<h4 id="heading-how-to-use-ejs-in-an-express-project">How to use EJS in an Express project</h4>
<p>The following sections will guide you through the process of using EJS in your Express.js project.</p>
<h5 id="heading-install-ejs">Install EJS</h5>
<p>First, install EJS in your Express project.</p>
<pre><code class="language-console">npm install ejs@6.0.1
</code></pre>
<p>Next, open your project's <code>server.js</code> module and configure the web server to serve the appropriate dynamically generated HTML view in response to requests.</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">// Add the Express and EJS modules
import express from "express";
import ejs from "ejs";

// Create a new Express application instance
const app = express();

// Specify the host and port to receive requests
const host = "localhost";
const port = 8000;

// Define the data object
const friendsData = {
  bestFriend: "Sarah",
  codingFriend: "Abraham",
  dreamFriend: "Mary",
};
const replacementObject = { friends: friendsData };

// Use backticks to define a template string with embedded JavaScript
const templateString = `
&lt;html&gt;
  &lt;body&gt;
    &lt;h1&gt;List of Friends&lt;/h1&gt;
    &lt;ul&gt;
    &lt;%# Loop through the friends object %&gt;
    &lt;% for (const eachFriend in friends) { -%&gt;
      &lt;li&gt;&lt;%= friends[eachFriend] %&gt; is my &lt;%= eachFriend %&gt;&lt;/li&gt;
    &lt;% } -%&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
&lt;/html&gt;
`;

// Compile and render the template string to HTML (the rendered view)
const htmlData = ejs.render(templateString, replacementObject);

// Use the dynamic view as a response to 'GET /' requests
app.get("/", (req, res) =&gt; res.send(htmlData));

// Run the server on the specified port and hostname
app.listen(port, host, () =&gt; {
  console.log(`Server running live at http://${host}:
${port}!`);
});
</code></pre>
<p>Here are the main things the snippet above does:</p>
<ul>
<li><p>Create an Express application instance to access Express APIs, such as routers and middleware, which simplify HTTP request handling in Node.js.</p>
</li>
<li><p>Render the template string once when the script starts to generate the HTML that the server sends to each client.</p>
</li>
<li><p>Create routes to receive and respond to clients' requests.</p>
</li>
<li><p>Use Express's <code>app.listen()</code> method to start the Node.js HTTP server on a specific port and execute a callback when the server begins listening for client requests.</p>
</li>
</ul>
<h5 id="heading-run-the-express-app">Run the Express app</h5>
<p>After setting up the server, run it with Node.js.</p>
<pre><code class="language-console">node --watch server.js
</code></pre>
<p>Afterward, check your app running live at <code>http://localhost:8000</code>.</p>
<p><strong>Tip:</strong> Stop the running process using <code>Ctrl + C</code> on Windows, macOS, or Linux.</p>
<p>To keep things organized, put all your view templates in a <code>views</code> directory. This is a common practice.</p>
<h5 id="heading-create-a-directory-for-view-templates">Create a directory for view templates</h5>
<p>Create a <code>views</code> directory at your project's root to store all view templates.</p>
<pre><code class="language-console">mkdir views
</code></pre>
<h5 id="heading-create-an-index-view-template">Create an index view template</h5>
<pre><code class="language-console">touch views/index.ejs
</code></pre>
<p><strong>Tip:</strong> EJS template files use the <code>.ejs</code> extension.</p>
<p>Open the file and move the HTML template from <code>server.js</code> into it.</p>
<p><code>views/index.ejs</code></p>
<pre><code class="language-ejs">&lt;html&gt;
  &lt;body&gt;
    &lt;h1&gt;List of Friends&lt;/h1&gt;
    &lt;ul&gt;
      &lt;%# Loop through the friends object %&gt;
      &lt;% for (const eachFriend in friends) { -%&gt;
      &lt;li&gt;&lt;%= friends[eachFriend] %&gt; is my &lt;%= eachFriend %&gt;&lt;/li&gt;
      &lt;% } -%&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<h5 id="heading-update-the-server-to-retrieve-view-templates-from-the-views-folder">Update the server to retrieve view templates from the <code>views</code> folder</h5>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import express from "express";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const app = express();
const host = "localhost";
const port = 8000;
const __dirname = dirname(fileURLToPath(import.meta.url));

// Specify the app's views directory
app.set("views", join(__dirname, "views"));

// Specify the app's view engine
app.set("view engine", "ejs");

// Define the data object
const friendsData = {
  bestFriend: "Sarah",
  codingFriend: "Abraham",
  dreamFriend: "Mary",
};
const replacementObject = { friends: friendsData };

// Compile and render the index view template to HTML and use it as a response to 'GET /' requests
app.get("/", (req, res) =&gt; {
  res.render("index", replacementObject);
});

// Run the server on the specified port and hostname
app.listen(port, host, () =&gt; {
  console.log(`Server running live at http://${host}:
${port}`);
});
</code></pre>
<p>The snippet above uses Express's <code>render()</code> method to generate HTML from the <code>index.ejs</code> template file.</p>
<p><strong>Note:</strong></p>
<ul>
<li>If you omit the <code>app.set("view engine", "ejs")</code> line, then the <code>render()</code> method's view template argument must include a file extension like this:</li>
</ul>
<pre><code class="language-javascript">app.get("/", (req, res) =&gt; {
  res.render("index.ejs", replacementObject);
});
</code></pre>
<ul>
<li><p>Express has no default template engine. Express also supports engines such as Pug (formerly called Jade), EJS, Mustache, and Handlebars.</p>
</li>
<li><p><code>app.set()</code> is the method for adding a key-value pair to the application's settings. You can retrieve the setting's value with <code>app.get()</code> as follows:</p>
</li>
</ul>
<pre><code class="language-javascript">app.set("my name", "Oluwatobi");

const bio = app.get("my name");

console.log(bio); // Outputs: "Oluwatobi"
</code></pre>
<h4 id="heading-how-to-create-reusable-ejs-templates-partials">How to create reusable EJS templates (partials)</h4>
<p>EJS provides the <code>include()</code> method for including (nesting) one view template into another.</p>
<p><strong>Tip:</strong> In EJS, partials are reusable templates.</p>
<h5 id="heading-syntax-of-the-include-method">Syntax of the include() method</h5>
<p>The <code>include()</code> method accepts two arguments. Here's the syntax:</p>
<pre><code class="language-ejs">&lt;%- include("path/to/partial", data) %&gt;
</code></pre>
<ul>
<li><p><code>"path/to/partial"</code>: (required) The path to the reusable template, relative to the current file (the parent template). For example, if the current file is at <code>"./views/index.ejs"</code> and the partial is at <code>"./views/partials/footer.ejs"</code>, the <code>include()</code> path argument would be <code>"partials/footer"</code>.</p>
</li>
<li><p><code>data</code>: (optional) An object containing the properties to pass to the partial.</p>
</li>
</ul>
<h5 id="heading-how-to-include-a-partial-in-a-view-template">How to include a partial in a view template</h5>
<p>Consider the following server file:</p>
<p><code>server.js</code></p>
<pre><code class="language-javascript">import express from "express";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";

const app = express();
const host = "localhost";
const port = 8080;
const __dirname = dirname(fileURLToPath(import.meta.url));

app.set("views", join(__dirname, "views"));
app.set("view engine", "ejs");

const friendsData = {
  bestFriend: "Sarah",
  codingFriend: "Abraham",
  dreamFriend: "Mary",
};
const replacementObject = { friends: friendsData };

app.get("/", (req, res) =&gt; {
  res.render("index", replacementObject);
});

app.listen(port, host, () =&gt; {
  console.log(`Server running live at http://${host}:
${port}`);
});
</code></pre>
<p>The snippet above will render an <code>index</code> template when users send a GET request to the <code>"/"</code> path. Below is the <code>index.ejs</code> template file.</p>
<p><code>views/index.ejs</code></p>
<pre><code class="language-ejs">&lt;html&gt;
  &lt;body&gt;
    &lt;h1&gt;List of Friends&lt;/h1&gt;
    &lt;ul&gt;
    &lt;%# Loop through the friends object %&gt;
    &lt;% for (const eachFriend in friends) { -%&gt;
      &lt;li&gt;&lt;%= friends[eachFriend] %&gt; is my &lt;%= eachFriend %&gt;&lt;/li&gt;
    &lt;% } -%&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>If you need the <code>&lt;li&gt;</code> element to be reusable in multiple templates, extract it into a separate file and use the <code>include()</code> method to add it to any template as needed. Here's how:</p>
<h5 id="heading-create-a-partials-directory">Create a partials directory</h5>
<p>Create a <code>partials</code> directory in your <code>views</code> folder to store all reusable view templates.</p>
<pre><code class="language-console">mkdir views/partials
</code></pre>
<h5 id="heading-create-a-partial-view-template">Create a partial view template</h5>
<p>Create a partial view template for the <code>&lt;li&gt;</code> element.</p>
<pre><code class="language-console">touch views/partials/friendLi.ejs
</code></pre>
<p>Open the file and add the <code>&lt;li&gt;</code> element.</p>
<p><code>views/partials/friendLi.ejs</code></p>
<pre><code class="language-ejs">&lt;li&gt;&lt;%= friend %&gt; is my &lt;%= friendType %&gt;&lt;/li&gt;
</code></pre>
<h5 id="heading-update-the-main-view-template">Update the main view template</h5>
<p>Open the <code>index.ejs</code> file and use the <code>include()</code> method to add the <code>friendLi.ejs</code> partial view template.</p>
<p><code>views/index.ejs</code></p>
<pre><code class="language-ejs">&lt;html&gt;
  &lt;body&gt;
    &lt;h1&gt;List of Friends&lt;/h1&gt;
    &lt;ul&gt;
    &lt;%# Loop through the friends object %&gt;
    &lt;% for (const eachFriend in friends) { -%&gt;
      &lt;%- include("partials/friendLi", { friend: friends[eachFriend], friendType: eachFriend }) %&gt;
    &lt;% } -%&gt;
    &lt;/ul&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Using <code>include()</code> to add the <code>&lt;li&gt;</code> element makes it reusable in multiple templates, rather than restricting it to the <code>index.ejs</code> view template.</p>
<h5 id="heading-run-your-server-from-the-root-directory">Run your server from the root directory</h5>
<pre><code class="language-console">node --watch server.js
</code></pre>
<p>Then, check your app running live at <code>http://localhost:8080</code>.</p>
<p><strong>Note:</strong> Although the steps above demonstrate EJS partials with a simple <code>&lt;li&gt;</code> element, you can use the same concept to reuse your application's navbar, footer, and other components across multiple view templates.</p>
<h2 id="heading-overview">Overview</h2>
<p>In this handbook, we explored the core concepts you need to start building applications with Node.js and Express.js. We discussed how Node.js works, its module support, and how to create HTTP servers. We also explored how Express.js simplifies server-side development through routes, routers, and views.</p>
<p>Whether you’re considering a small personal project or a full-stack application for a larger user base, you now have a solid starting point for building with Node.js and Express.js.</p>
<p>Thanks for reading!</p>
<h3 id="heading-dive-deeper-into-nodejs-and-expressjs">Dive Deeper into Node.js and Express.js</h3>
<p>This handbook has given you a peek inside my <a href="https://www.amazon.com/dp/B0HK23L2Y1?tag=codesweetly00-20">Node.js and Express.js Simplified book</a>.</p>
<p>Whether you’re learning backend development for the first time, expanding your JavaScript skills beyond frontend development, or looking for a practical introduction to Node.js and Express.js, the book will help you build on what you’ve learned here and develop the skills to create, test, and deploy complete applications.</p>
<p>You’ll dive deeper into Node.js and Express.js through practical explanations and hands-on examples covering topics such as file management, file uploads, forms, sessions, frontend-to-backend communication, testing, TypeScript, and deployment.</p>
<p><a href="https://www.amazon.com/dp/B0HK23L2Y1?tag=codesweetly00-20"><img src="https://cdn.hashnode.com/uploads/covers/61672d1653401f641ba159b4/bcad7d15-53d7-4ba7-8974-b424c50c01a0.jpg" alt="Build with Node.js &amp; Express.js: A practical, beginner-friendly guide to building, testing, and deploying web applications" style="display: block;" width="970" height="250" loading="lazy"></a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How CSS content-visibility Works and How It Can Improve Rendering Performance ]]>
                </title>
                <description>
                    <![CDATA[ What happens when a page has 150 content-heavy cards, but the user can only see the first few? You might expect the browser to only worry about what's currently visible. But this isn't exactly what ha ]]>
                </description>
                <link>https://www.freecodecamp.org/news/css-content-visibility-rendering-performance/</link>
                <guid isPermaLink="false">6abdfcd2e3ca1b6f34c584aa</guid>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web performance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Frontend Development ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Ayman Eldawy ]]>
                </dc:creator>
                <pubDate>Thu, 01 Oct 2026 06:00:00 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/f11711dc-ac4a-43f0-b312-4d89c6f7f989.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>What happens when a page has 150 content-heavy cards, but the user can only see the first few?</p>
<p>You might expect the browser to only worry about what's currently visible. But this isn't exactly what happens.</p>
<p>Content can be thousands of pixels below the viewport, and the browser may still have rendering work to do for it.</p>
<p>So I wanted to try something. What if we could basically tell the browser:</p>
<blockquote>
<p>You don't need to render all of this right now. Skip the work for content the user can't see yet.</p>
</blockquote>
<p>CSS has a property that can help us do exactly that in one line:</p>
<pre><code class="language-css">.card {
  content-visibility: auto;
}
</code></pre>
<p>Which naturally made me curious about how much difference it could actually make.</p>
<p>So instead of stopping at the documentation, I built a page with <strong>150 content-heavy cards</strong>, opened Chrome DevTools, and measured it.</p>
<p>The result was much bigger than I expected. But it also introduced another problem.</p>
<p>Let's start with what <code>content-visibility</code> is actually asking the browser to do.</p>
<h3 id="heading-what-well-cover">What We'll Cover:</h3>
<ul>
<li><p><a href="#heading-what-does-content-visibility-auto-actually-do">What Does <code>content-visibility: auto</code> Actually Do?</a></p>
</li>
<li><p><a href="#heading-i-built-a-page-with-150-cards">I Built a Page With 150 Cards</a></p>
</li>
<li><p><a href="#heading-we-saved-rendering-work-now-the-layout-has-a-problem">We Saved Rendering Work. Now the Layout Has a Problem.</a></p>
</li>
<li><p><a href="#heading-wait-isnt-this-just-lazy-loading">Wait, Isn't This Just Lazy Loading?</a></p>
</li>
<li><p><a href="#heading-but-what-about-accessibility">But What About Accessibility?</a></p>
</li>
<li><p><a href="#heading-so-when-is-content-visibility-actually-worth-using">So, When Is <code>content-visibility</code> Actually Worth Using?</a></p>
</li>
</ul>
<h3 id="heading-prerequisites">Prerequisites</h3>
<p>To follow along with this article, you should have:</p>
<ul>
<li><p>A basic understanding of HTML and CSS</p>
</li>
<li><p>A modern browser such as Chrome</p>
</li>
<li><p>Basic familiarity with Chrome DevTools</p>
</li>
</ul>
<p>You don't need any framework knowledge. The experiment uses plain HTML, CSS, and JavaScript so we can focus specifically on the browser's rendering behavior.</p>
<h2 id="heading-what-does-content-visibility-auto-actually-do">What Does <code>content-visibility: auto</code> Actually Do?</h2>
<p>The <code>content-visibility</code> property controls whether an element renders its contents.</p>
<p>For this experiment, we're interested in one value:</p>
<pre><code class="language-css">.card {
  content-visibility: auto;
}
</code></pre>
<p>With <code>auto</code> the browser can skip rendering work for an element's contents when that element isn't currently relevant to the user, such as when it's far outside the viewport.</p>
<p>The important part is that we're talking about <strong>rendering</strong>.</p>
<p>The element hasn't been removed from the DOM. And <code>content-visibility</code> isn't primarily telling the browser not to download its resources.</p>
<p>We're giving the browser an opportunity to avoid rendering work that isn't useful yet.</p>
<p>This works through CSS containment. As the <a href="https://web.dev/articles/content-visibility">web.dev guide</a> explains, <code>content-visibility: auto</code> applies layout, style, and paint containment. When the contents aren't relevant to the user, the browser can skip more of the work for that subtree.</p>
<p>So without <code>content-visibility</code>, the browser may still do rendering work for content far below the viewport. With it, some of that work can be skipped until the content becomes relevant.</p>
<p>Notice the word <strong>can</strong>.</p>
<p><code>content-visibility: auto</code> doesn't guarantee that every element outside the viewport will always have its rendering work skipped. The browser determines whether the contents are relevant to the user and whether their rendering can be skipped.</p>
<p>This sounds useful. But useful by how much?</p>
<p>Time to measure it.</p>
<h2 id="heading-i-built-a-page-with-150-cards">I Built a Page With 150 Cards</h2>
<p>I didn't want to test this on a tiny demo where the difference might disappear into measurement noise.</p>
<p>So I deliberately made the page a little ridiculous. It contains <strong>150 content-heavy cards</strong>.</p>
<p>Each card has:</p>
<ul>
<li><p>a fixed-size image placeholder</p>
</li>
<li><p>a heading and tags</p>
</li>
<li><p>eight paragraphs</p>
</li>
<li><p>ten related items</p>
</li>
</ul>
<p>The number 150 isn't special.</p>
<p>A page doesn't suddenly become a good candidate for <code>content-visibility</code> because it crosses some element-count threshold.</p>
<p>For example, 150 simple <code>&lt;div&gt;</code> elements may give the browser very little expensive work to skip.</p>
<p>But 150 sections containing nested layout, text, lists, images, and other rendering work create a much better opportunity.</p>
<p>For this experiment, that's exactly what I wanted.</p>
<p>I also used plain HTML, CSS, and JavaScript instead of React or another framework.</p>
<p>That was intentional.</p>
<p>If we're testing a CSS rendering optimization, adding framework execution gives us another variable we don't need.</p>
<p>Here's the JavaScript that generates the cards:</p>
<pre><code class="language-jsx">const CARD_COUNT = 150;
const PARAGRAPHS_PER_CARD = 8;
const RELATED_ITEMS_PER_CARD = 10;

const cards = [];

for (let i = 1; i &lt;= CARD_COUNT; i++) {
  cards.push(`
    &lt;article class="card"&gt;
      &lt;div class="card-image-placeholder"&gt;&lt;/div&gt;

      &lt;h2&gt;Product ${i}&lt;/h2&gt;

      ${Array.from(
        { length: PARAGRAPHS_PER_CARD },
        (_, index) =&gt; `
          &lt;p&gt;
            Product ${i}, paragraph ${index + 1}.
            This is sample content used to make
            each card more expensive to render.
          &lt;/p&gt;
        `
      ).join("")}

      &lt;ul&gt;
        ${Array.from(
          { length: RELATED_ITEMS_PER_CARD },
          (_, index) =&gt; `
            &lt;li&gt;Related item ${index + 1}&lt;/li&gt;
          `
        ).join("")}
      &lt;/ul&gt;
    &lt;/article&gt;
  `);
}

document.querySelector("#feed").innerHTML = cards.join("");
</code></pre>
<p>I considered using real images, but that would make the experiment messier.</p>
<p>Network latency, caching, and image decoding could all influence what we see.</p>
<p>So each card uses a CSS placeholder instead:</p>
<pre><code class="language-css">.card-image-placeholder {
  height: 320px;
  background: linear-gradient(
    135deg,
    #e5e7eb,
    #f3f4f6
  );
}
</code></pre>
<p>For each configuration, I kept the browser environment and viewport size the same, and I didn't scroll during the initial-load recording.</p>
<p>I also repeated the tests instead of picking the nicest-looking run.</p>
<p>If you want to reproduce the experiment, I've published the complete example on <a href="https://github.com/AymanEldawy/content-visibility-benchmark">GitHub here</a>.</p>
<p>It contains the same test page and configurations used for the measurements below, so you can run the experiment yourself and compare the results on your own browser and device.</p>
<p>Now we have something to measure.</p>
<h3 id="heading-first-the-baseline">First, the Baseline</h3>
<p>Before adding <code>content-visibility</code>, I recorded the page three times using the Chrome DevTools Performance panel.</p>
<p>The <strong>Rendering</strong> activity reported in the <strong>Performance</strong> recording was:</p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Rendering</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>39 ms</td>
</tr>
<tr>
<td>2</td>
<td>44 ms</td>
</tr>
<tr>
<td>3</td>
<td>42 ms</td>
</tr>
<tr>
<td><strong>Median</strong></td>
<td><strong>42 ms</strong></td>
</tr>
</tbody></table>
<p>I used the median rather than choosing the fastest run.</p>
<p>There's one important clarification here. These numbers represent the Rendering activity reported in the DevTools Performance recording.</p>
<p>They're <strong>not</strong> total page-load time, a Core Web Vital, or a direct measurement of user-perceived performance.</p>
<p>Chrome DevTools reports Rendering as one category in the activity breakdown of a Performance recording, which is why I'll keep referring specifically to the <strong>Rendering activity</strong> rather than saying the page "rendered in 42 ms."</p>
<p>So our baseline was:</p>
<blockquote>
<p><strong>Median Rendering activity: 42 ms</strong></p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/6a9c0329ac57d79e893e710c/668c7d7f-5218-4d47-9fc9-4b8ed83a2ec7.png" alt="Chrome DevTools Performance recording showing Rendering activity for the baseline test without content-visibility." style="display: block;" width="650" height="567" loading="lazy">

<p>One baseline Performance recording. The <strong>42 ms median</strong> above was calculated from three separate runs.</p>
<p>Then I changed exactly one thing:</p>
<pre><code class="language-css">.card {
  content-visibility: auto;
}
</code></pre>
<p>And ran the experiment again.</p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Rendering</th>
</tr>
</thead>
<tbody><tr>
<td>1</td>
<td>20 ms</td>
</tr>
<tr>
<td>2</td>
<td>21 ms</td>
</tr>
<tr>
<td>3</td>
<td>20 ms</td>
</tr>
<tr>
<td><strong>Median</strong></td>
<td><strong>20 ms</strong></td>
</tr>
</tbody></table>
<p>Okay. That's not subtle.</p>
<p>We went from:</p>
<pre><code class="language-plaintext">42 ms → 20 ms

Or: 

(42 - 20) / 42 × 100 ≈ 52%
</code></pre>
<p>In this experiment, adding <code>content-visibility: auto</code> was associated with roughly a <strong>52% reduction in the Rendering activity reported by Chrome DevTools</strong>.</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a9c0329ac57d79e893e710c/20c7e8a7-979f-407e-a8ec-73a106d9e97c.png" alt="Chrome DevTools Performance recording after applying content-visibility: auto to the cards." style="display: block;" width="1063" height="934" loading="lazy">

<p><strong>But we need to be careful with that number.</strong></p>
<p>This doesn't mean <code>content-visibility</code> makes websites 52% faster. It doesn't even mean the entire page loaded 52% faster.</p>
<p>We measured one category of activity inside Chrome DevTools using one deliberately content-heavy page in one test environment.</p>
<p>The result will depend on things like</p>
<ul>
<li><p>how much below-the-fold content you have</p>
</li>
<li><p>how expensive that content is to render</p>
</li>
<li><p>the browser</p>
</li>
<li><p>the device</p>
</li>
<li><p>the viewport</p>
</li>
<li><p>the structure of the page</p>
</li>
</ul>
<p>Our experiment was basically designed to give <code>content-visibility</code> a lot of work to skip.</p>
<p>So the useful conclusion isn't</p>
<blockquote>
<p>"<code>content-visibility</code> makes websites 52% faster."</p>
</blockquote>
<p>It's this:</p>
<blockquote>
<p>On pages with substantial off-screen content, allowing the browser to skip unnecessary rendering work can produce a measurable improvement.</p>
</blockquote>
<img src="https://cdn.hashnode.com/uploads/covers/6a9c0329ac57d79e893e710c/80afb8bc-ef49-48e0-96eb-f6dda04be6a2.png" alt="Diagram showing content-visibility rendering visible cards inside the viewport while allowing rendering work for off-screen cards to be skipped." style="display: block;" width="1536" height="1024" loading="lazy">

<p>web.dev has demonstrated the same idea with its own content-heavy demo and reported a large improvement there as well.</p>
<p>But their number belongs to their test. Our number belongs to ours.</p>
<p>Neither is a percentage you should copy into your own application without measuring it.</p>
<p>But our experiment isn't finished yet. Because after I started scrolling, another problem appeared.</p>
<h2 id="heading-we-saved-rendering-work-now-the-layout-has-a-problem">We Saved Rendering Work. Now the Layout Has a Problem.</h2>
<p>Think about what we've just told the browser: a card is far below the viewport, so its contents can be skipped.</p>
<p>Fair enough. But the page still needs a layout.</p>
<p>So here's the awkward question: <strong>How much space should an off-screen card occupy before the browser knows its normally rendered size?</strong></p>
<p>If the browser's initial geometry doesn't match the card's actual size, the layout can adjust when the card becomes relevant and its contents are rendered.</p>
<p>That's where <code>contain-intrinsic-size</code> comes in.</p>
<p>We can give the browser a fallback intrinsic size:</p>
<pre><code class="language-css">.card {
  content-visibility: auto;
  contain-intrinsic-size: auto 900px;
}
</code></pre>
<p>The <code>900px</code> value gives the browser a fallback intrinsic size to use when the contents are skipped and no remembered rendered size is available.</p>
<p>But the <code>auto</code> part makes this more interesting.</p>
<p>Imagine the card hasn't been normally rendered yet. The browser doesn't have a previous size to reuse, so our <code>900px</code> value can act as the fallback.</p>
<p>Later, the card gets close enough to the viewport and is normally rendered. Now the browser has seen its actual rendered size.</p>
<p>If that card becomes skippable again, the browser can reuse the remembered size instead of falling back to <code>900px</code>.</p>
<p>So:</p>
<pre><code class="language-css">contain-intrinsic-size: auto 900px;
</code></pre>
<p>doesn't mean the browser somehow knows the card is <code>900px</code> tall.</p>
<p>It means:</p>
<img src="https://cdn.hashnode.com/uploads/covers/6a9c0329ac57d79e893e710c/4ae68781-d2c5-4ec8-af7b-0f9487102f34.png" alt="Flowchart showing how contain-intrinsic-size uses a remembered rendered size when available, or a 900px fallback when no remembered size exists." style="display: block;" width="1378" height="1464" loading="lazy">

<p>This is also useful alongside <code>content-visibility</code>.</p>
<p>If we're skipping the contents, we still need reasonable geometry for the page before those contents are rendered.</p>
<h3 id="heading-so-what-should-the-fallback-be">So What Should the Fallback Be?</h3>
<p>My first question was whether choosing a smaller or larger fallback would noticeably affect the initial Rendering measurement.</p>
<p>So I tried three values:</p>
<table>
<thead>
<tr>
<th>Fallback</th>
<th>Rendering</th>
</tr>
</thead>
<tbody><tr>
<td>100px</td>
<td>12 ms</td>
</tr>
<tr>
<td>900px</td>
<td>10 ms</td>
</tr>
<tr>
<td>2000px</td>
<td>11 ms</td>
</tr>
</tbody></table>
<p>Those results are very close.</p>
<p>At this scale, the differences are small enough that I wouldn't treat them as evidence that one fallback value is faster than another.</p>
<p>We can't look at this and conclude:</p>
<blockquote>
<p>"Smaller intrinsic sizes are faster."</p>
</blockquote>
<p>We also can't conclude:</p>
<blockquote>
<p>"The estimate closest to the actual size will always have the best rendering performance."</p>
</blockquote>
<p>That's not really the job of the fallback.</p>
<p>The more useful question is what happens to the layout.</p>
<p>If your fallback is <code>100px</code>, but the actual card turns out to be much taller, the page may need to adjust its geometry when the contents are rendered.</p>
<p>The opposite can happen if your fallback is much larger than the actual content.</p>
<p>So you want a reasonable approximation, not a magic performance number.</p>
<p>But while testing this, I noticed something I wasn't expecting.</p>
<p>With only</p>
<pre><code class="language-css">.card {
  content-visibility: auto;
}
</code></pre>
<p>I later ran three measurements:</p>
<pre><code class="language-plaintext">20 ms
21 ms
20 ms

Median: 20 ms
</code></pre>
<p>Then I added:</p>
<pre><code class="language-css">.card {
  content-visibility: auto;
  contain-intrinsic-size: auto 900px;
}
</code></pre>
<p>And got:</p>
<pre><code class="language-plaintext">10 ms
9 ms
12 ms

Median: 10 ms
</code></pre>
<p>So yes, in this particular experiment, adding the explicit fallback was associated with another reduction in Chrome DevTools' Rendering activity.</p>
<p>Tempting conclusion:</p>
<pre><code class="language-plaintext">contain-intrinsic-size = 2× faster
</code></pre>
<p>Nope. Our measurement tells us what happened in this experiment.</p>
<p>It doesn't establish a general performance characteristic of <code>contain-intrinsic-size</code>.</p>
<p>Its job is to provide useful intrinsic geometry when size containment applies, including a fallback when no remembered normally rendered size is available.</p>
<p>There's another reason to be careful with these numbers. The original baseline comparison used three runs, while these later exploratory measurements used three runs.</p>
<p>That's fine for something I noticed while experimenting. It's not the controlled methodology I'd use to claim that one configuration is generally faster than another.</p>
<p>So the <code>10 ms</code> result stays exactly what it is: <strong>an interesting observation from this experiment.</strong> Not a browser guarantee.</p>
<h3 id="heading-did-we-just-move-the-work-to-scrolling">Did We Just Move the Work to Scrolling?</h3>
<p>There's another question the initial-load benchmark doesn't answer.</p>
<p>If we're skipping work for off-screen cards, some of those cards will eventually become relevant when the user scrolls.</p>
<p>The work hasn't magically disappeared. Some of it has been deferred until the browser decides the content is relevant.</p>
<p>So did we improve the whole experience, or did we just move some work somewhere else?</p>
<p>I don't have a benchmark from this experiment that answers that.</p>
<p>I didn't record a controlled scrolling test, so I'm not going to turn what I saw while manually scrolling into another performance claim.</p>
<p>A separate experiment would need to look at scrolling, cards becoming relevant, layout shifts, and frame behavior while moving through the page.</p>
<p>For now, our measurement tells us something much narrower:</p>
<blockquote>
<p><code>content-visibility: auto</code> reduced the initial Rendering activity measured in this particular test.</p>
</blockquote>
<p>It doesn't tell us that every part of the browsing experience became 52% faster. And that's an important boundary for the numbers we're looking at.</p>
<h2 id="heading-wait-isnt-this-just-lazy-loading">Wait, Isn't This Just Lazy Loading?</h2>
<p>At this point, <code>content-visibility</code> can sound suspiciously similar to lazy loading.</p>
<p>Both are trying to avoid unnecessary work. But they're generally avoiding <strong>different work</strong>.</p>
<p>Lazy loading is mostly asking:</p>
<blockquote>
<p>Do I need to load this resource yet?</p>
</blockquote>
<p><code>content-visibility</code> is asking something different:</p>
<blockquote>
<p>Do I need to render these contents yet?</p>
</blockquote>
<p>Take an image:</p>
<pre><code class="language-html">&lt;img
  src="/product.jpg"
  loading="lazy"
  alt="Black running shoes"
&gt;
</code></pre>
<p>Native image lazy loading can defer loading that resource until it's closer to being needed.</p>
<p>But with:</p>
<pre><code class="language-css">.product-card {
  content-visibility: auto;
}
</code></pre>
<p>The element can already exist in the DOM, and its resources may already have been loaded.</p>
<p>We're asking the browser whether it needs to perform the rendering work for those contents yet.</p>
<p>So these optimizations aren't necessarily alternatives.</p>
<p>You could have both on the same page.</p>
<ul>
<li><p>One can help avoid loading a resource too early.</p>
</li>
<li><p>The other can help avoid rendering work that isn't currently necessary.</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/6a9c0329ac57d79e893e710c/8df3b443-5d39-4707-bad2-4b21a45c3850.png" alt="Diagram showing two page performance strategies: lazy loading delays loading resources such as images and JavaScript, while content-visibility can defer layout and painting for off-screen content." style="display: block;" width="1312" height="1199" loading="lazy">

<h2 id="heading-but-what-about-accessibility">But What About Accessibility?</h2>
<p>There's an interesting detail about <code>content-visibility: auto</code> that's easy to miss.</p>
<p>Off-screen content whose rendering is being skipped remains in the DOM and can remain available in the accessibility tree.</p>
<p>That's useful for performance, but it also gives us an important boundary: <code>content-visibility: auto</code> <strong>is a rendering optimization. It isn't a semantic hiding mechanism.</strong></p>
<p>If your goal is to hide content from assistive technologies, don't use <code>content-visibility</code> for that job. Use the appropriate HTML, CSS, and accessibility semantics instead.</p>
<p>There's also an edge case worth knowing about. web.dev points out that content inside a skipped subtree can still appear in the accessibility tree even when some of that content would normally be hidden by styles such as <code>display: none</code> or <code>visibility: hidden</code>.</p>
<p>So if you're applying <code>content-visibility</code> to complex or interactive sections, test the actual keyboard and assistive-technology experience instead of assuming a rendering optimization can't affect accessibility.</p>
<h2 id="heading-so-when-is-content-visibility-actually-worth-using">So, When Is <code>content-visibility</code> Actually Worth Using?</h2>
<p>After all these measurements, the answer is less exciting than <em>adding</em> <em>this one CSS property can make</em> <em>your website fast</em>.</p>
<p>Which is probably a good sign.</p>
<p><code>content-visibility: auto</code> becomes interesting when your page contains a meaningful amount of expensive content outside the viewport.</p>
<p>You can think:</p>
<ul>
<li><p>long article or social feeds</p>
</li>
<li><p>large product listings</p>
</li>
<li><p>documentation pages with many sections</p>
</li>
<li><p>long dashboards</p>
</li>
<li><p>complex below-the-fold sections</p>
</li>
</ul>
<p>If your page is small and nearly everything is visible immediately, there may simply not be much rendering work to skip.</p>
<p>And before using it in production, there's one practical question left: <strong>Can you rely on browser support?</strong></p>
<p>For modern browsers, support is broad. <code>content-visibility</code> is part of Baseline 2024, so unless your project needs to support older browser versions, compatibility is much less of a concern than it used to be.</p>
<p>So <code>content-visibility</code> isn't something you need on every page. But when a page contains a lot of expensive off-screen content, it gives the browser something valuable: <strong>the option to simply not render work the user can't see yet.</strong></p>
<h3 id="heading-references">References</h3>
<ul>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/content-visibility">MDN content-visibility</a></p>
</li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/contain-intrinsic-size">MDN contain-intrinsic-size</a></p>
</li>
<li><p><a href="https://web.dev/articles/content-visibility">web.dev content-visibility</a></p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Build a Real-Time Word Counter Tool with HTML, CSS, and JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Whether you're writing an essay, a tweet, or a blog post, keeping track of your word and character count is very important. In this tutorial, you'll build a fully functional, real-time Word Counter to ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-build-a-real-time-word-counter-tool-with-html-css-and-javascript/</link>
                <guid isPermaLink="false">6abca43ca3fbe2215db75ecf</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ HTML5 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ CSS ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Beginner Developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Bansidhar Kadiya ]]>
                </dc:creator>
                <pubDate>Wed, 30 Sep 2026 05:55:08 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/uploads/covers/5e1e335a7a1d3fcc59028c64/d32feb51-3930-4bd7-be76-9a9150d069d1.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Whether you're writing an essay, a tweet, or a blog post, keeping track of your word and character count is very important.</p>
<p>In this tutorial, you'll build a fully functional, real-time Word Counter tool from scratch. You'll use HTML for the structure, CSS for a clean design, and vanilla JavaScript to handle the counting logic.</p>
<p>Because this tool runs completely in the browser, it works instantly as you type and keeps your text data completely private.</p>
<p>Let's get started.</p>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To follow this guide easily, you should have:</p>
<ul>
<li><p>A basic understanding of HTML tags and CSS styling.</p>
</li>
<li><p>Familiarity with JavaScript concepts like functions, event listeners, and basic Regular Expressions (Regex).</p>
</li>
<li><p>A code editor (like VS Code) and a web browser.</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a href="#heading-step-1-set-up-your-project">Step 1: Set Up Your Project</a></p>
</li>
<li><p><a href="#heading-step-2-build-the-html-structure">Step 2: Build the HTML Structure</a></p>
<ul>
<li><a href="#heading-understanding-the-html">Understanding the HTML:</a></li>
</ul>
</li>
<li><p><a href="#heading-step-3-style-the-tool-with-css">Step 3: Style the Tool with CSS</a></p>
<ul>
<li><a href="#heading-understanding-the-css">Understanding the CSS:</a></li>
</ul>
</li>
<li><p><a href="#heading-step-4-add-the-javascript-logic">Step 4: Add the JavaScript Logic</a></p>
<ul>
<li><a href="#heading-understanding-the-javascript">Understanding the JavaScript:</a></li>
</ul>
</li>
<li><p><a href="#heading-step-5-test-your-application">Step 5: Test Your Application</a></p>
</li>
</ul>
<h2 id="heading-step-1-set-up-your-project">Step 1: Set Up Your Project</h2>
<p>First, you need to set up your workspace. Create a new folder on your computer and name it <code>word-counter-app</code>.</p>
<p>Inside this folder, create three empty files:</p>
<ul>
<li><p><code>index.html</code></p>
</li>
<li><p><code>style.css</code></p>
</li>
<li><p><code>script.js</code></p>
</li>
</ul>
<h2 id="heading-step-2-build-the-html-structure">Step 2: Build the HTML Structure</h2>
<p>Open your <code>index.html</code> file. You need to create a layout that includes a header, a grid to display the real-time statistics, a text area for the user to type in, and buttons to copy or clear the text.</p>
<p>Add the following code into your HTML file:</p>
<pre><code class="language-html">&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
    &lt;title&gt;Word Counter Tool&lt;/title&gt;
    &lt;link rel="stylesheet" href="style.css"&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;header class="header-section"&gt;
        &lt;h1&gt;Word Counter&lt;/h1&gt;
        &lt;p class="description"&gt;Paste or type your text below to get a real-time count of words, characters, sentences, and paragraphs.&lt;/p&gt;
    &lt;/header&gt;

    &lt;main class="tool-container"&gt;
        
        &lt;!-- Statistics Panel --&gt;
        &lt;div class="stats-grid"&gt;
            &lt;div class="stat-box"&gt;
                &lt;div class="stat-value" id="wordCount"&gt;0&lt;/div&gt;
                &lt;div class="stat-label"&gt;Words&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="stat-box"&gt;
                &lt;div class="stat-value" id="charCount"&gt;0&lt;/div&gt;
                &lt;div class="stat-label"&gt;Characters&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="stat-box"&gt;
                &lt;div class="stat-value" id="sentenceCount"&gt;0&lt;/div&gt;
                &lt;div class="stat-label"&gt;Sentences&lt;/div&gt;
            &lt;/div&gt;
            &lt;div class="stat-box"&gt;
                &lt;div class="stat-value" id="paragraphCount"&gt;0&lt;/div&gt;
                &lt;div class="stat-label"&gt;Paragraphs&lt;/div&gt;
            &lt;/div&gt;
        &lt;/div&gt;

        &lt;!-- User Input Area --&gt;
        &lt;textarea id="textInput" placeholder="Start typing or paste your text here..."&gt;&lt;/textarea&gt;

        &lt;!-- Action Buttons --&gt;
        &lt;div class="controls"&gt;
            &lt;button class="btn-primary" onclick="copyText()" id="copyBtn"&gt;Copy Text&lt;/button&gt;
            &lt;button class="btn-secondary" onclick="clearText()"&gt;Clear&lt;/button&gt;
        &lt;/div&gt;

    &lt;/main&gt;

    &lt;script src="script.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Understanding the HTML:</p>
<ul>
<li><p><strong>The</strong> <code>.stats-grid</code><strong>:</strong> This holds four separate boxes to show the counts. Each number has a unique <code>id</code> (like <code>wordCount</code>) so JavaScript can find and update it easily.</p>
</li>
<li><p><strong>The</strong> <code>&lt;textarea&gt;</code><strong>:</strong> This is the main input box where users will type or paste their content.</p>
</li>
<li><p><strong>The</strong> <code>&lt;script&gt;</code> <strong>tag:</strong> This connects your HTML to the logic you will write in the next steps.</p>
</li>
</ul>
<h2 id="heading-step-3-style-the-tool-with-css">Step 3: Style the Tool with CSS</h2>
<p>Next, you'll give your tool a modern, professional look. You'll use CSS Grid to align the statistics boxes perfectly.</p>
<p>Open your <code>style.css</code> file and add this code:</p>
<pre><code class="language-css">:root {
    --primary-color: #007bff;
    --bg-color: #f8f9fa;
    --text-dark: #202124;
    --text-muted: #5f6368;
    --border-color: #dadce0;
    --panel-bg: #ffffff;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
    background-color: var(--bg-color);
    color: var(--text-dark);
    margin: 0;
    padding: 40px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.header-section {
    text-align: center;
    margin-bottom: 30px;
}

h1 {
    font-size: 2.5rem;
    margin: 0 0 10px 0;
    font-weight: 800;
}

p.description {
    color: var(--text-muted);
    max-width: 600px;
    margin: 0 auto;
    line-height: 1.6;
    font-size: 1.1rem;
}

.tool-container {
    background-color: var(--panel-bg);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    padding: 24px;
    width: 100%;
    max-width: 900px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}

/* Stats Grid */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
}

.stat-box {
    background-color: var(--bg-color);
    border: 1px solid var(--border-color);
    border-radius: 8px;
    padding: 16px;
    text-align: center;
}

.stat-value {
    font-size: 2rem;
    font-weight: 700;
    color: var(--primary-color);
    margin-bottom: 4px;
}

.stat-label {
    font-size: 0.9rem;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.5px;
    font-weight: 600;
}

/* Text Area */
textarea {
    width: 100%;
    height: 250px;
    padding: 16px;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    font-size: 1rem;
    line-height: 1.6;
    resize: vertical;
    box-sizing: border-box;
    font-family: inherit;
    margin-bottom: 20px;
    transition: border-color 0.2s ease;
}

textarea:focus {
    outline: none;
    border-color: var(--primary-color);
}

/* Buttons */
.controls {
    display: flex;
    gap: 12px;
}

button {
    padding: 10px 20px;
    font-size: 1rem;
    font-weight: 600;
    border-radius: 6px;
    cursor: pointer;
    border: none;
    transition: background-color 0.2s ease;
}

.btn-primary {
    background-color: var(--primary-color);
    color: #ffffff;
}

.btn-primary:hover {
    background-color: #0056b3;
}

.btn-secondary {
    background-color: transparent;
    color: var(--text-dark);
    border: 1px solid var(--border-color);
}

.btn-secondary:hover {
    background-color: var(--bg-color);
}
</code></pre>
<p>Understanding the CSS:</p>
<ul>
<li><p><strong>CSS Grid:</strong> The <code>.stats-grid</code> class uses <code>grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));</code>. This makes the four stat boxes automatically stack neatly on top of each other if a user views the tool on a small mobile screen.</p>
</li>
<li><p><strong>CSS Variables:</strong> Using <code>:root</code> at the top allows you to quickly change the brand color later if you want to use something other than the default blue (<code>#007bff</code>).</p>
</li>
</ul>
<p>At this point, the visual design of your tool is complete. Here's what the final Word Counter will look like in your browser:</p>
<img src="https://cdn.hashnode.com/uploads/covers/699c7b22cf5def0f6aaf982b/dc292767-ac0f-4e87-b88c-d64fab38f370.png" alt="Word Counter Tool" style="display: block;" width="1435" height="843" loading="lazy">

<h2 id="heading-step-4-add-the-javascript-logic">Step 4: Add the JavaScript Logic</h2>
<p>Now you need to make the tool count the text. You'll use an event listener that watches every keystroke. Every time the user types, it recalculates the words, characters, sentences, and paragraphs.</p>
<p>Open your <code>script.js</code> file and paste this code:</p>
<pre><code class="language-javascript">const textInput = document.getElementById('textInput');
const wordCountDisplay = document.getElementById('wordCount');
const charCountDisplay = document.getElementById('charCount');
const sentenceCountDisplay = document.getElementById('sentenceCount');
const paragraphCountDisplay = document.getElementById('paragraphCount');
const copyBtn = document.getElementById('copyBtn');

// 1. Listen for user input in real-time
textInput.addEventListener('input', updateStatistics);

// 2. The Core Counting Logic
function updateStatistics() {
    const text = textInput.value;

    // Character Count (includes spaces)
    charCountDisplay.textContent = text.length;

    // Word Count
    const words = text.match(/\S+/g) || [];
    wordCountDisplay.textContent = words.length;

    // Sentence Count
    const sentences = text.split(/[.!?]+(?=\s|$)/).filter(sentence =&gt; sentence.trim().length &gt; 0);
    sentenceCountDisplay.textContent = sentences.length;

    // Paragraph Count
    const paragraphs = text.split(/\n+/).filter(paragraph =&gt; paragraph.trim().length &gt; 0);
    paragraphCountDisplay.textContent = paragraphs.length;
}

// 3. Copy functionality
function copyText() {
    if (!textInput.value) return;
    
    textInput.select();
    document.execCommand('copy');
    
    // Provide visual feedback
    copyBtn.textContent = 'Copied!';
    setTimeout(() =&gt; {
        copyBtn.textContent = 'Copy Text';
    }, 1500);
}

// 4. Clear functionality
function clearText() {
    textInput.value = '';
    updateStatistics(); // Reset counts to zero
}
</code></pre>
<p>Understanding the JavaScript:</p>
<ul>
<li><p><strong>The</strong> <code>input</code> <strong>Event:</strong> <code>textInput.addEventListener('input', ...)</code> is the secret to real-time updates. It triggers the counting function the exact moment a key is pressed or text is pasted.</p>
</li>
<li><p><strong>Counting Words:</strong> <code>text.match(/\S+/g)</code> is a Regular Expression that looks for unbroken strings of non-whitespace characters. This is much more accurate than just splitting the text by spaces, because it ignores extra empty spaces left by mistake.</p>
</li>
<li><p><strong>Counting Sentences:</strong> The <code>.split(/[.!?]+(?=\s|$)/)</code> logic cuts the text into pieces every time it sees a period, exclamation mark, or question mark followed by a space.</p>
</li>
</ul>
<h2 id="heading-step-5-test-your-application">Step 5: Test Your Application</h2>
<p>You're completely done coding! Now it's time to verify that your logic works correctly.</p>
<ol>
<li><p>Open your <code>word-counter-app</code> folder.</p>
</li>
<li><p>Double-click the <code>index.html</code> file to open it in your web browser.</p>
</li>
<li><p>Type a few sentences into the text area. Watch the numbers at the top update instantly.</p>
</li>
<li><p>Try adding double spaces or hitting the "Enter" key to make new paragraphs, and ensure the logic counts them accurately.</p>
</li>
<li><p>Click <strong>Copy Text</strong> to test the clipboard feature, and <strong>Clear</strong> to reset the board.</p>
</li>
</ol>
<p>By completing this project, you've built a fast, client-side utility tool using pure vanilla JavaScript. You learned how to manipulate strings, use Regular Expressions for text analysis, and create responsive UI grids.</p>
<p>If you want to see this exact codebase running in a live production environment, you can try out this <a href="https://99tools.net/word-counter/">Online Word Counter</a>. Keep building, and happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
