Stable unique ids like React.useId() but in Astro
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:
- A plain module-level counter. It keeps counting across pages, so the ids on a page depend on which pages were rendered before it. That brings back the build-to-build differences I wanted to remove, and it breaks if rendering order or concurrency changes.
- A
Mapkeyed on the scope. It gives each page its own counter, but aMapholds strong references to its keys. Every page’sAstro.localsobject would stay in memory until the process ends. - A property on
Astro.locals. It works without any module state, but it mutates an object I do not own and needs a type declaration. - A
WeakMapkeyed on the scope. Each page gets its own counter, the helper keeps its state private, and the entry becomes collectable once the render is done and nothing else references the scope.
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.
- React:
useId()generates ids for accessibility attributes. With server rendering it requires an identical component tree on the server and the client. It also cannot be used in async Server Components. - Vue:
useId()generates ids that are unique per call and per component instance. They are stable across server and client renders, so there are no hydration mismatches. - Svelte:
$props.id()generates an id unique to the component instance. When hydrating a server-rendered component, the value is consistent between server and client.
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
- I verified this for a static build. On-demand rendering also worked in the dev server with concurrent requests, but I have not tested a production adapter.
- Ids are unique per page, not across pages. That is all a document needs.
- Ids depend on render order. Adding a component earlier in the page shifts the ids of later ones. That only matters if something outside the page, like a link with a fragment, relies on a generated id. If it does, use a fixed id instead.
- Call
uniqueIdbefore anyawaitin the frontmatter. Async components render concurrently, so after anawaitthe ids follow completion time, not document order. In a test with four async components, calling it after theawaitgaveid-1to the fastest one. Calling it before gave document order.