Skip to content

SPA, SSR and hydration

Angular TransferState in the HTML: read ng-state, expect renames

Find and parse the JSON an Angular SSR page embeds for hydration, read its HttpClient cache entries, and match the script by type and content, not by its id.

By Cerys Eaton, SiteRender team · Published

This article was drafted with AI assistance from the sources listed below and edited and published by the SiteRender team.

Reading Angular TransferState without a browser
  • Fetch the raw HTML and look near the end of the body
  • Match script tags with type application/json, not only id ng-state
  • Accept any id that ends in -state: APP_ID sets the prefix
  • JSON.parse the content; escaped < and / decode on their own
  • Read entries by their u field, not by the hashed key
  • Compare with the visible text before you trust a field

You fetched an Angular page without a browser and the main text is not where you expected. Before you start Chrome, look at the bottom of the body. An Angular app rendered on the server can ship the data it loaded as JSON in the same response, so the browser does not have to ask for it again.

This post shows where that JSON sits, how to parse it, and why a lookup by id="ng-state" is the wrong test.

Where the state script is written

Symptom: the raw HTML ends with a long <script> that does not run any code.

curl -s https://example.com/ -o raw.html
grep -oE '<script[^>]*-state"[^>]*>' raw.html

On Angular's server side, the platform-server package creates a <script> element, sets type="application/json" and gives it the id appId + '-state'. It appends it to doc.body, and a comment in the source says it is added "at the very bottom" on purpose. When the store is empty, the function returns early and writes no tag.

The default application ID is ng, set by the APP_ID token. So an app that does not set its own carries ng-state. No match: either nothing was transferred, or the id has another prefix. Read on before you decide.

What the content looks like

The core TransferState class is a key-value store. Its toJson() runs JSON.stringify on the store and then replaces every < with \u003C and every / with \u002F. The comments give the reasons: the first keeps the content from breaking out of the script tag, the second keeps crawlers from indexing relative URLs inside the JSON.

Two things follow for a reader:

  • A standard JSON parser reads the content as is. The escapes are ordinary JSON escapes, and the strings come back with their slashes.
  • The content cannot contain a literal </script>, so a non-greedy match up to the next </script> gets the whole payload.

The class comment also says what survives: booleans, numbers, strings, null and non-class objects round-trip without loss. Anything else does not.

HttpClient cache entries: short keys, hashed names

On apps that use HttpClient during the server render, the store also holds HttpClient's transfer cache. In transfer_cache.ts, each entry uses one- and two-letter keys:

KeyField
bbody
hheaders
sstatus
ststatus text
urequest URL
rtresponse type

The name of each entry is not the URL. Angular joins the method, response type, request URL, serialized body and encoded params with \0, and hashes the result with a SHA-256 routine that outputs a 64-character hex string. You cannot look a request up by its address; iterate the values and read u.

Other details from the same file: by default only GET, HEAD and QUERY requests are cached; requests with Authorization, Proxy-Authorization or Cookie headers are skipped unless the app opts in; arraybuffer and blob bodies are stored as base64. So b is the body the server-side render received from that request.

Why the id can change

A page can carry a state script under another name for two reasons.

First, the APP_ID comment says that when several applications are bootstrapped on one page, each needs its own APP_ID. Since the id is built from it, each app's state script has its own prefix.

Second, a security advisory. GHSA-rgjc-h3x7-9mwg (CVE-2026-54267, @angular/core), published in June 2026, describes DOM clobbering of the state lookup: if an app puts user input into an element's id before the real script is parsed, document.getElementById('ng-state') can return the attacker's element, and HttpClient can serve forged responses from TransferState. The patched versions are 22.0.1, 21.2.17 and 20.3.25. For teams that cannot update yet, one workaround sets a unique APP_ID, which the advisory says changes the lookup from ng-state to unique-obfuscated-app-id-state.

So a scraper that hard-codes ng-state can break on a site that applied that workaround, with no change you can see on the page. Angular's own reader checks the tag name too: it uses the element only if tagName is SCRIPT and it has text.

Match by type and content

The parser below takes every application/json script, parses it and prefers objects whose id ends in -state and whose values look like cache entries. The entry test is a heuristic built from the keys above, not an Angular API.

import json, re, sys, urllib.request

url = sys.argv[1] if len(sys.argv) > 1 else "https://example.com/"
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
html = urllib.request.urlopen(req, timeout=30).read().decode("utf-8", "replace")

best = None
for m in re.finditer(r"<script\b([^>]*)>(.*?)</script>", html, re.S | re.I):
    attrs, body = m.group(1), m.group(2)
    if not re.search(r"type=[\"']?application/json", attrs, re.I):
        continue
    id_m = re.search(r"\bid=[\"']?([\w-]+)", attrs)
    sid = id_m.group(1) if id_m else ""
    try:
        data = json.loads(body)
    except ValueError:
        continue
    if not isinstance(data, dict):
        continue
    entries = [v for v in data.values() if isinstance(v, dict) and "b" in v]
    score = (sid.endswith("-state"), len(entries))
    if best is None or score > best[0]:
        best = (score, sid, data, entries)

if best is None or best[0] == (False, 0):
    sys.exit("no Angular state script found")
_, sid, data, entries = best
print(f"script id={sid!r}, {len(data)} keys, {len(entries)} cache entries")
for e in entries:
    print(e.get("s"), e.get("u"), type(e["b"]).__name__)

example.com is not an Angular site, so this exits with "no Angular state script found". On an Angular page you are allowed to read, each line shows a status, a request URL and the type of the stored body.

Rules that keep this safe

  • It is an implementation detail. The short keys come from Angular's source, not a documented format. Check the shape and fail loudly when it changes.
  • Read what the page shows. The cache can hold API fields the page never displays. Use what is published, and respect robots.txt and the site's terms.
  • The page wins. When the JSON and the visible text disagree, trust the text.

The SPA, SSR and hydration guide covers what other frameworks send first, and the Nuxt payload post shows a format that parses as JSON but needs a second step.

Test it yourself

Run the grep on an Angular page. One -state script: parse it and compare three u entries with what the page displays. Several: the page hosts more than one app. None, and the text is missing from the HTML: the data is fetched after load, and that page needs a browser.

Frequently asked questions

Where does Angular put TransferState in the server-rendered HTML?

In a script element with type application/json at the very end of the body. Its id is the application ID followed by -state, so with the default application ID ng it is ng-state. If the store is empty, Angular writes no script at all.

Why is the ng-state script missing or named differently on some Angular pages?

Either nothing was stored during the server render, or the app sets its own APP_ID, which changes the prefix of the id. A June 2026 Angular security advisory, CVE-2026-54267, lists a unique APP_ID as a workaround, which turns ng-state into a name like unique-obfuscated-app-id-state.

Can I parse Angular TransferState with a normal JSON parser?

Yes. Angular serializes the store with JSON.stringify and only replaces the characters < and / with their \u escapes, which a JSON parser decodes. Class instances do not survive the round trip; booleans, numbers, strings, null and plain objects do.

What are the short keys like b, h, s and u in Angular's state JSON?

They are HttpClient transfer cache entries. In Angular's source, b is the response body, h the headers, s the status, st the status text, u the request URL and rt the response type. The entry's own key is a hash of the request, so match entries by u.

Sources

  1. platform-server transfer_state.ts (Angular source) (Documentation)
  2. core transfer_state.ts (Angular source) (Documentation)
  3. HttpClient transfer_cache.ts (Angular source) (Documentation)
  4. APP_ID token, application_tokens.ts (Angular source) (Documentation)
  5. GHSA-rgjc-h3x7-9mwg: Angular client hydration DOM clobbering (CVE-2026-54267) (News)