swjh
All posts

Stable unique ids like React.useId() but in Astro

⬪6 min read
astrojssnippet

HTML that links other elements by id (<label for>, aria-labelledby, popovertarget, …) needs an id that is unique on the page. crypto.randomUUID() works, but it makes the HTML differ on every build.
Frameworks like React, Vue, etc. provide useId() helpers to solve this out of the box, but Astro does not, so here’s a small helper.

The problem with random ids

A random id changes on every build, which breaks caching of unchanged pages. So while random ids work in general, using them in a static site generator like Astro is far from ideal.

Solution: a counter keyed on Astro.locals

Astro.locals is a fresh object for each page render, as far as I can tell (the docs do not state this explicitly). A WeakMap keyed on it holds one counter per page. The counter restarts for every page, and the weak key lets it be garbage collected with the render.

// utils/uniqueId.ts

/** Counter for each scope, stored by scope object. Weak keys let a scope (and its counter) be garbage collected. */
const idCounters = new WeakMap<object, number>();

/**
 * Generates a deterministic id, unique within a scope.
 * Safe for SSR/static output (no randomness, so no hydration or build diffs).
 *
 * Utils can't access `Astro` directly, so in components pass `Astro.locals`
 * (a fresh object per page render) to restart the counter on every page.
 *
 * Call it before any `await`. After an `await`, concurrently rendered
 * siblings get ids in completion order, which can change between builds.
 *
 * @param scope - Object that owns the counter, e.g. `Astro.locals`.
 * @param prefix - Id prefix. Defaults to `"id"`.
 * @returns Id like `id-1`, `id-2`, ...
 * @example
 * const id = uniqueId(Astro.locals, "id"); // "id-1"
 */
export function uniqueId(scope: object, prefix: string = "id"): string {
  const next = (idCounters.get(scope) ?? 0) + 1;
  idCounters.set(scope, next);
  return `${prefix}-${next}`;
}

Utils cannot access Astro directly, so the component passes the scope in. Here’s a usage Example:

---
// TableOfContents.astro
const headingId = uniqueId(Astro.locals);
---

<nav aria-labelledby={headingId}>
  <h2 id={headingId}>Table of Contents</h2>
  <!-- ... -->
</nav>

Each page starts at id-1, and ids are unique within a page.

Why a WeakMap?

The helper lives in a module, and a module is loaded once per build process. All pages are rendered by that same process, so any state in the module is shared by every page. The state has to be tied to one render somehow. These are the alternatives I considered:

The last one is the smallest option that meets all three goals: per-page, private, no leak.

How other tools solve it

This is a common enough problem that most component frameworks ship a primitive for it. They all avoid randomness for the same reason: the id has to be identical on the server and in the browser.

All three need to agree between two renders of the same component. An Astro component renders once on the server and ships no JavaScript by default, so no hydration step has to match. A per-render counter is enough. If you use islands, prefer the framework’s own primitive inside the island.

Demo

Each field below calls uniqueId(Astro.locals) once. Every label is wired to its input by the generated id.

id="id-1"
id="id-2"
id="id-3"

Limits