Skip to content

fix(@angular/ssr): harden platform destruction and abort/response cleanup guards - #34781

Open
alan-agius4 wants to merge 2 commits into
angular:mainfrom
alan-agius4:fix/ssr-abort-destroy-followups
Open

alan-agius4 wants to merge 2 commits into
angular:mainfrom
alan-agius4:fix/ssr-abort-destroy-followups

Conversation

@alan-agius4

Copy link
Copy Markdown
Collaborator

PR Checklist

PR Type

  • Bugfix

What is the current behavior?

Follow-up hardening after #34768 (related to #34754 / #34777):

  • getRoutesFromAngularRouterConfig() calls platformRef.destroy() directly in finally without checking !platformRef.destroyed or catching destroy-hook errors, which can throw NG0404, fail route extraction, or mask errors thrown inside try.
  • renderAngular() checks platformRef.destroyed and applicationRef.destroyed, but does not check applicationRef.injector.destroyed (or destroyPromise before content()), which can still throw NG0205 if the environment injector is marked destroyed before ApplicationRef.ngOnDestroy() completes.
  • writeResponseToNodeResponse() returns early when the Node destination is already closed/destroyed without cancelling source.body.
  • createAngularSsrInternalMiddleware() wraps createWebRequestFromNodeRequest(req) with { signal: AbortSignal.timeout(30_000) }, replacing the client-disconnect AbortSignal instead of combining both signals.

What is the new behavior?

  • Guard platformRef.destroy() in getRoutesFromAngularRouterConfig() with if (!platformRef.destroyed) and catch/log destroy-hook errors via console.error.
  • Check destroyPromise, platformRef.destroyed, applicationRef.destroyed, applicationRef.injector.destroyed, and signal?.aborted consistently across renderAngular() and content() (and replace silent early-return guards in ng_spec.ts with node:assert).
  • Cancel unlocked source.body streams (with error logging) when writeResponseToNodeResponse() returns early on an already-closed Node response.
  • Combine nodeWebReq.signal and AbortSignal.timeout(30_000) using AbortSignal.any() in createAngularSsrInternalMiddleware().

Does this PR introduce a breaking change?

  • No

@alan-agius4 alan-agius4 added the target: patch This PR is targeted for the next patch release label Nov 24, 2026
@alan-agius4
alan-agius4 requested a review from dgp1130 November 24, 2026 08:17
@alan-agius4 alan-agius4 added the action: review The PR is still awaiting reviews from at least one requested reviewer label Nov 24, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request improves SSR request handling and lifecycle management by ensuring that SSR requests are aborted on client disconnect or timeout, response bodies are cancelled when the destination is closed, and platform/injector destruction is handled gracefully. The review feedback highlights two important robustness improvements: providing a fallback for AbortSignal.any to support Node.js versions prior to v20.3.0, and using optional chaining when accessing destination.req.url to prevent potential TypeErrors.

Comment on lines +66 to 69
const nodeWebReq = createWebRequestFromNodeRequest(req);
const webReq = new Request(nodeWebReq, {
signal: AbortSignal.any([nodeWebReq.signal, AbortSignal.timeout(30_000)]),
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Using AbortSignal.any directly will throw a TypeError in Node.js versions prior to v20.3.0 (such as Node.js v18.19.1+, which is officially supported by Angular 19). To prevent runtime crashes in these environments, please provide a fallback implementation when AbortSignal.any is not available.

      const nodeWebReq = createWebRequestFromNodeRequest(req);
      const timeoutSignal = AbortSignal.timeout(30_000);
      const signal = typeof AbortSignal.any === 'function'
        ? AbortSignal.any([nodeWebReq.signal, timeoutSignal])
        : (() => {
            const controller = new AbortController();
            const abort = () => controller.abort();
            if (nodeWebReq.signal.aborted || timeoutSignal.aborted) {
              controller.abort();
            } else {
              nodeWebReq.signal.addEventListener('abort', abort, { once: true });
              timeoutSignal.addEventListener('abort', abort, { once: true });
            }
            return controller.signal;
          })();
      const webReq = new Request(nodeWebReq, { signal });

Comment on lines +44 to +52
if (source.body && !source.body.locked) {
await source.body.cancel().catch((err) => {
// eslint-disable-next-line no-console
console.error(
`An error occurred while cancelling the response body for: ${destination.req.url}.`,
err,
);
});
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Accessing destination.req.url directly can throw a TypeError if destination.req is undefined (e.g., in mock environments or if the request/response has been fully torn down). Using optional chaining prevents potential crashes in this error-handling path.

Suggested change
if (source.body && !source.body.locked) {
await source.body.cancel().catch((err) => {
// eslint-disable-next-line no-console
console.error(
`An error occurred while cancelling the response body for: ${destination.req.url}.`,
err,
);
});
}
if (source.body && !source.body.locked) {
await source.body.cancel().catch((err) => {
// eslint-disable-next-line no-console
console.error(
`An error occurred while cancelling the response body for: ${destination.req?.url ?? 'unknown'}.`,
err,
);
});
}

…uards

- Guard `platformRef.destroy()` in `getRoutesFromAngularRouterConfig`
  against already-destroyed platforms and catch/log destroy-hook errors
  so route extraction neither fails nor masks earlier errors.
- Check `applicationRef.injector.destroyed` and `destroyPromise`
  consistently across `renderAngular` bootstrap, stability, and
  `content()` guards.
- Cancel unlocked `source.body` streams when
  `writeResponseToNodeResponse` returns early for an already-closed
  Node response.
Combine the client-disconnect `AbortSignal` from
`createWebRequestFromNodeRequest` with `AbortSignal.timeout(30_000)`
using `AbortSignal.any` instead of replacing the client signal in
`createAngularSsrInternalMiddleware`.
@alan-agius4
alan-agius4 force-pushed the fix/ssr-abort-destroy-followups branch from 413cdfa to 930d82e Compare November 24, 2026 08:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

action: review The PR is still awaiting reviews from at least one requested reviewer area: @angular/build area: @angular/ssr target: patch This PR is targeted for the next patch release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant