In `getParentBlockHydrationQueue`, PR #58722 breaks out of the ancestor loop
before calling `hydrationQueue.unshift(currentBlockId)` when it encounters an
ancestor `@defer` block that is already hydrating. Because of that,
`hydrationQueue` never contains the hydrating ancestor, only the unhydrated
descendants below it.
`triggerHydrationFromBlockName` still contains a `hydrationQueue.shift()` added
in PR #60203 under the assumption that the hydrating parent sat at index 0.
When `parentBlockPromise` is non-null, that shifts off the first unhydrated
child block instead: in a 2-level nested `@defer` block it empties the queue
and drops the replay event, and in a 3-level hierarchy (immediate inside
interaction inside immediate) it drops the middle block so both inner blocks
stay dehydrated.
Remove the stale `hydrationQueue.shift()` call and add regression specs in
`incremental_hydration_spec.ts`.
Consider the following template:
```html
<main>
@if (show) {
<span>text</span>
}
</main>
```
During hydration, Angular looks for the comment node that marks where the
`@if` block (or an `<ng-container>`) is. If the HTML from the server was
changed and this comment is missing, dev mode throws a clear NG0502 error.
But this check only runs in dev mode.
Prior to this fix, production continued with the missing comment and failed
later with a raw error that doesn't say what went wrong:
```
TypeError: Cannot set properties of null (setting '__ngContext__')
```
With this fix, production also throws NG0502.
`triggerHydrationForBlockQueue` accessed `blocksBeingHydrated.get(dehydratedBlockId)` with a non-null assertion `!.resolve()`. If the entry was cleaned up while the function was suspended awaiting resource loading or next render, this resulted in an unhandled `TypeError: Cannot read properties of undefined (reading 'resolve')`.
Additionally, the pending task added by `pendingTasks.add()` was not guarded by a `try/finally`, causing the task to leak and permanently breaking application stability whenever hydration encountered an error or threw an exception.
This commit optional-chains `.resolve()` matching sibling accesses and wraps the queue processing loop in `try/finally` so `pendingTasks.remove(taskId)` is always invoked.
Fixes#71769
In one of our applications, we saw memory growing with event replay enabled,
while removing `withEventReplay()` always made the issue go away.
We then found that the `<body>` event listeners added through the inline event
dispatch script were never removed. Angular replayed the early events and
dropped `window._ejsas[appId]`, but those listeners were still pushing events
to the old queue. Nothing was reading that queue again (in the global script).
With this fix, clearing the early event contract also removes its event
listeners, so they can no longer stay attached.
Closes#71518
Resolves the TODO(incremental-hydration) in the same function. An audit of the remaining defer instructions found no other sites: 20 run in the create block, and ɵɵdeferWhen/ɵɵdeferPrefetchWhen already keep their lookups inside the guard
Component instances with identical hydration annotations share the same serialized data, so consuming the ICU case queue in place left it empty for every later instance and their ICU content was rendered twice.
Please note that this change addresses a **real** production issue
observed, rather than a speculative issue identified through
AI-assisted code analysis.
There is no open issue because most people never put two apps with the
same APP_ID on one page.
Prior to this commit, if you bootstrap 2 apps simultaneously, i.e. a
real app + a widget coming from a CDN (the code we don't have control
of, but we only configure the app name in their settings):
```text
TypeError: Cannot read properties of undefined (reading 'c')
```
With this fix, the code no longer fails with a raw type error. It warns
with code NG0511 instead. It does not crash explicitly, because that
might break whenStable().
Removes unnecessary `changeDetection: ChangeDetectionStrategy.Eager` from test components where default `OnPush` change detection works or where state updates can use signals, removes unnecessary `provideZoneChangeDetection()`, replaces `fixture.detectChanges()` with `await fixture.whenStable()` where appropriate, and cleans up redundant `forwardRef`/`CommonModule` imports and unused selectors.
Allow `scrollMargin` to be configured for `@defer` viewport, prefetch, and
hydrate triggers.
Unlike `rootMargin`, `scrollMargin` expands the clipping bounds of nested scroll
containers. This allows deferred content to be loaded or prefetched before it
enters the visible area of a nested scroller.
Include `scrollMargin` in the IntersectionObserver cache key so viewport
triggers with different margins use the correct observer configuration.
Previously, resolveUrl only checked whether the raw URL string started with '//' before WHATWG URL resolution. When given an input such as '/.//evil.test', WHATWG dot-segment normalization popped the leading '/.', leaving a pathname starting with '//'. This corrupted ServerPlatformLocation and led to protocol-relative open redirects in SSR.
Now, resolveUrl also verifies that the normalized URL pathname does not start with '//' when allowProtocolRelative is false.
Fixes#71076
Before, when hydration couldn't find a server-rendered element, the error
only gave a tag name and a raw tNode index (e.g. `tNode #27`), which is
meaningless without dev-mode source maps. Now it resolves the enclosing
component's host element and includes it in the message, so there's
actually something to search the codebase for.
lView[HOST] covers the normal case. Embedded views (from `@if`/`@for`)
don't have a host of their own, so we fall back to
lView[DECLARATION_COMPONENT_VIEW]?.[HOST].
The descriptive message stays dev-mode only, as usual for RuntimeError
messages, so it's stripped from production bundles.
Avoid String.prototype.trim() when classifying server request URLs because it
strips Unicode whitespace that WHATWG URL parsing preserves as path data.
This mismatch can cause xhr2 to send credentials to a different origin than
the application approved.
Classify the unmodified request URL so whitespace-prefixed input falls through
URL resolution, and cover NBSP- and BOM-prefixed HTTP URLs.
Fixes#70540
This fixes a production crash seen on pages that dynamically create
non-defer components:
TypeError: Cannot set properties of null (setting '__ngContext__')
...
at locateOrCreateElementNodeImpl
The crash was traced to `triggerHydrationForBlockQueue()`. When a
`@defer` block finishes hydrating, it removes its own `PendingTasks`
entry and immediately calls `cleanupHydratedDeferBlocks()` ->
`cleanupDehydratedViews()`. That cleanup walks all LViews registered
with `ApplicationRef` and removes dehydrated views that aren't
associated with a defer block. This isn't safe while other async
hydration work is still pending.
For example, a dynamically created component can have its own
`PendingTasks` entry while its `ViewContainerRef.createComponent()`
call is still waiting to run. If an unrelated defer block finishes
first, its cleanup can remove that component's dehydrated view before
the component gets a chance to claim it. The later creation then sees
stale hydration state and can fail with the crash above.
The same race shows up with the router. A `@defer (hydrate ...)` block
in the app shell can hydrate while a lazy route is still loading. The
router outlet hasn't claimed its server-rendered DOM yet, so the
cleanup deletes it and the page is rebuilt from scratch, which looks
like a flicker on first paint. It also hits a `PendingTasks`-guarded
`createComponent()` that lives inside the hydrating block itself.
This was reproduced with tests in `incremental_hydration_spec.ts`: an
immediately hydrated `@defer` block next to an unrelated
`PendingTasks`-guarded `ViewContainerRef.createComponent()` whose
creation is delayed until after the defer block hydrates, a shell
`@defer` block next to a lazy route, and a `createComponent()` inside
the hydrating block. All of them fail with the original code and pass
with this fix.
The fix waits for `ApplicationRef.whenStable()` before running the
cleanup, but only when there are other pending tasks. This keeps the
usual case synchronous while making sure cleanup doesn't run while
other hydration work is still in progress. The app can be destroyed
while the cleanup waits, so the cleanup is skipped in that case, the
same way the bootstrap cleanup does it.
The wait is intentionally conditional. An unconditional `whenStable()`
introduces another subscription to the shared stability signal.
Because this subscription is created after this function removes its
own pending task, callers that are already waiting on `whenStable()`
can resume one microtask before this cleanup does. That changes the
existing timing and breaks the `immediate` and `should create an
IntersectionObserver...` tests. Checking `hasPendingTasks` first
avoids creating that extra subscription when there is nothing else to
wait for, preserving the existing behavior.
Fixes#70796
Under the WHATWG URL standard, HTTP and HTTPS URLs lacking an authority
(e.g., `http:/path` or `http:path`) resolve as relative paths when resolved
against an origin of the same scheme. Previously, `relativeUrlsTransformerInterceptorFn`
treated any URL with a scheme as an absolute URL, bypassing base resolution in SSR
and allowing Node fetch to parse the path as a cross-origin host.
This commit updates SSR URL resolution and the HTTP interceptor to ensure
HTTP(S) URLs without an authority are resolved against the current origin,
preventing unexpected origin changes and aligning SSR with browser behavior.
Fixes#70447
This started from a real production crash trace:
TypeError: Cannot read properties of null (reading 'nextSibling')
Traced through a minified bundle back to siblingAfter() in
packages/core/src/hydration/node_lookup_utils.ts. It walks forward a
fixed number of DOM siblings during hydration, based on how many the
server rendered. Its only guard, validateSiblingNodeExists(), is
gated behind ngDevMode and stripped from production builds. If the
client DOM has fewer real siblings than the server-serialized data
expects — client/server render diverged, or something outside
Angular (a browser extension, an injected script) removed a node —
the loop ran fully unguarded in production: currentNode went null
partway through, and the next iteration's currentNode.nextSibling
threw a raw, uncoded TypeError instead of a coded, debuggable one.
Reproduced first, not just theorized: added a test that server-
renders a @for loop with 3 items, removes 2 of them before hydration
runs, and confirmed it actually throws that exact TypeError against
the original code before touching anything.
Fix: add a null check at the top of the loop, matching the pattern
already used for the existing NG0500/NG0502 hydration checks in
element.ts — the dev-mode check runs first as before (a no-op in
production), and the new check is a pure safety net that only fires
once that dev-mode check has already been compiled away. In dev mode
this is provably dead code, so nothing about dev behavior changes.
Coded as NG0501 (HYDRATION_MISSING_SIBLINGS, already existed).
While investigating, found and fixed two more call sites with the
exact same shape of bug — a dev-only check that leaves production
completely unguarded:
- navigateToNode() (same file): walks an explicit "firstChild /
nextSibling" navigation path recorded for nodes that can't rely on
simple sibling-walking (e.g. content right after an <ng-content>
slot). Its only guard was also ngDevMode-only. Added the same
production safety net, both mid-loop (the raw-crash case) and
post-loop (where it could previously return null silently despite
the function's return type promising a non-null RNode). New code:
NG0509 (HYDRATION_MISSING_NODE_ON_PATH).
- getParentRElement() (render3/node_manipulation.ts): typed its
tNode parameter as always non-null, but a real production trace
showed it can be null at runtime, crashing on tNode.parent with no
useful information. Widened the type to TNode | null and added a
guard that throws a coded error instead. New code: NG0510
(PARENT_NODE_NOT_FOUND).
Unlike the other two, this one isn't gated behind ngDevMode at all
in the original code — it reproduces unconditionally. Decoded the
actual production minified stack trace against this source
(matched every frame character-for-character) to find the real
cause instead of guessing: an @if/@switch branch's content is its
own embedded template with its own TView, built lazily the first
time that branch renders. If an error interrupts that first pass —
here, a hydration mismatch on the branch's second child, after the
first child's TNode was already created — TView.firstCreatePass
still gets flipped to false in render.ts's `catch` block before the
error propagates, permanently marking that TView as corrupted.
Unlike a component's TView (rebuilt from scratch next time via
getOrCreateComponentTView()'s incompleteFirstPass check), nothing
rebuilds an embedded view's TView. The next time that exact branch
is selected again, its instructions read straight from the
corrupted tView.data instead of creating a fresh TNode, and any
node past the interruption point is still null.
The real test added for this (full_app_hydration_spec.ts) exercises
that whole chain for real: a hydration mismatch on an @if branch's
second child, then re-entering the same branch. Confirmed it throws
the exact byte-for-byte production error message ("Cannot read
properties of null (reading 'parent')") without the fix, and the
coded NG0510 with it. This replaces an earlier synthetic unit test
that just cast a variable to null to bypass the type system rather
than reproducing the actual failure.
Note: a more thorough fix would rebuild the corrupted embedded TView
itself (mirroring getOrCreateComponentTView()), which does make the
crash disappear — but doing that surfaces a second, separate bug:
the aborted first attempt's partially-created LView/DOM is never
torn down, so the retried branch's content gets appended alongside
leftover orphaned nodes instead of replacing them, corrupting
content silently instead of crashing loudly. That's a materially
bigger fix (proper LView cleanup after a mid-creation exception) and
is intentionally out of scope here; this commit keeps the narrower,
safe fix (a clear coded error) rather than trading a loud crash for
silent data corruption.
Along the way, deduplicated describeDomNode(), which existed as two
near-identical private copies (one in this file's own NG0500 check,
one in platform-browser's dom_renderer.ts insertBefore check) and
moved it into core's hydration/error_handling.ts, shared via the
private ɵdescribeDomNode export.
That function was then removed from every production code path
entirely, per review feedback: computing a human-readable node
description is debug-oriented work that shouldn't ship unconditionally
in production bundles, regardless of how cheap it is — production
should get the bare coded error only, the same as everywhere else in
this file. All three fixes above follow that: ngDevMode && 'message'
in production, no computed description. Confirmed the removal
actually shrinks output, not just assumed it: regenerated all 8
affected bundling symbol goldens, and each one shows exactly one
symbol removed — "describeDomNode" — and nothing else.
locateOrCreateElementNodeImpl looks up the DOM node for an element
during hydration and immediately checks its nodeType. If the
client-rendered DOM has fewer nodes than the server-rendered HTML,
the lookup returns null, and in production that null flows straight
into the nodeType check and crashes with a raw, uncoded
"Cannot read properties of null (reading 'nodeType')" TypeError.
The dev-mode check that would normally catch this (validateMatchingNode)
already handles a missing node, but it's compiled out of production
builds, so the crash only shows up outside of dev mode.
Add a null check ahead of the nodeType check that throws a coded
RuntimeError using the existing HYDRATION_MISSING_NODE (NG0502) code,
with a descriptive message in dev mode and a cheap fallback in
production. Also add a regression test that removes a server-rendered
element before hydration runs and asserts a coded RuntimeError is
thrown instead of a raw TypeError.
When hydration locates the DOM node for an ɵɵelementStart/ɵɵdomElementStart
instruction, locateOrCreateElementNodeImpl assumed the located node was
always an Element and called hasSkipHydrationAttrOnRElement(native), which
does native.hasAttribute(...). The check that would normally catch this
class of mismatch, validateMatchingNode, is gated behind `ngDevMode &&` and
is compiled out of production builds. So when a real SSR/hydration
structural mismatch located a Text or Comment node instead of the expected
Element, production builds hit .hasAttribute on a node type that doesn't
have it and crashed with a raw, uncoded TypeError instead of a coded
hydration-mismatch RuntimeError.
Add a cheap, always-on nodeType check ahead of that call. On mismatch it
throws RuntimeError(HYDRATION_NODE_MISMATCH, ngDevMode && '...'), the same
pattern used elsewhere in the codebase, so the descriptive message is only
built in dev mode and production keeps throwing just the bare NG0500 code
without pulling validateMatchingNode's DOM-printing machinery into the
production bundle (verified via the bundling/hydration golden-symbols test,
which is unchanged).
Treat MathML-namespaced script elements as scripts during template preprocessing. This prevents scripts nested in MathML HTML integration points from surviving template compilation.
Fixes#69785
Add an Angular SSR integration test in platform-server verifying that null input values do not render string attributes like value="null" during server-side rendering, while normal non-empty string values like value="hello" are properly preserved.
After incremental hydration became tree-shakable, application bootstrap could finish before a routed component activated the runtime. The one-time trigger scan was then skipped, leaving routed and nested hydration triggers uninitialized.
Coordinate application bootstrap with runtime activation and initialize once both have occurred.
Fixes#69908
Add a dedicated error reference page for NG05703 (suspicious URL origin
change during SSR) and update the error to use RuntimeError with a
negative code so the error message automatically includes a link to the
docs page in both dev and production builds.
Update affected tests in url_spec.ts, platform_location_spec.ts, and
integration_spec.ts to match the new NG05703-prefixed error message
format.
Fixes: #69667
Add allowOriginChange option to ResolveUrlOptions in resolveUrl to enforce same-origin validation on resolved URLs. When set to false, it prevents any cross-origin changes (including HTTP/HTTPS URLs), aligning the emulated server-side platform location environment with browser security behavior.
Refactor ServerPlatformLocation.replaceState to use allowOriginChange: false instead of manual comparison, hardening state change validation against cross-origin URLs.
Add unit tests in url_spec.ts and platform_location_spec.ts for the origin validation changes.
PR Close#69184
Update platform-server to use Angular 's native `RuntimeError` class.
This aligns error throwing patterns in platform-server with other packages of the framework such as core, common, and platform-browser.
For URL and host errors, the error messages are configured to return only the raw dynamic URL when `ngDevMode` is false (in production) to aid in troubleshooting without bloating production bundles.
PR Close#69184
Currently, the platform-server attempts to neutralize URL hijacking and SSRF
bypasses by collapsing multiple leading slashes in relative paths. However,
sophisticated bypasses using obfuscated protocols (e.g., carriage returns or
newlines) or relative-like backslash paths can still lead to unexpected
origin takeovers.
This commit improves security by doing the following:
- Rejects protocol-relative URLs by throwing an error if they are not
explicitly permitted via `allowProtocolRelative`.
- Strictly validates resolved URLs against the provided origin using
`isSafeOriginChange`. If a URL unexpectedly shifts origins, an error
is thrown.
- Permits origin changes only when standard absolute http/https protocols are
explicitly declared in the input URL.