Skip to content

fix(core): safely handle server platform destruction on aborted SSR requests - #72139

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

alan-agius4 wants to merge 11 commits into
angular:mainfrom
alan-agius4:fix-ssr-abort-destroy

Conversation

@alan-agius4

@alan-agius4 alan-agius4 commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

PR Checklist

PR Type

  • Bugfix

What is the current behavior?

When an SSR server immediately destroys PlatformRef on request abort (e.g. via @angular/ssr), several framework paths can crash the Node.js process with uncaughtException or unhandledRejection, or leave in-flight requests open:

  • bootstrap() looks up ENABLE_ROOT_COMPONENT_BOOTSTRAP after ApplicationInitStatus.donePromise without checking envInjector.destroyed, throwing NG0205.
  • ApplicationInitStatus does not unsubscribe observable initializers or settle donePromise when destroyed.
  • INTERNAL_APPLICATION_ERROR_HANDLER throws via setTimeout(() => { throw e; }) when injector.destroyed and no prior error has cached userErrorHandler, terminating Node.js SSR servers.
  • PendingTasks.run() reports post-destroy promise rejections to ErrorHandler.
  • FetchBackend does not abort in-flight fetch requests on DestroyRef.onDestroy, and emitting complete() on stream cancellation triggers EmptyError in firstValueFrom/lastValueFrom.
  • Router.dispose() does not unsubscribe active setupNavigations transitions, leaving guards and resolvers running after platform teardown.
  • renderInternal() reports rejections from async BEFORE_APP_SERIALIZED hooks and calls renderToString() even if the platform was destroyed mid-hook.

Related issue: angular/angular-cli#34754

What is the new behavior?

  • @angular/core:
    • ApplicationInitStatus unsubscribes observable initializers on DestroyRef.onDestroy, settles donePromise without setting done = true, stops remaining initializers if destroyed, and ignores late post-destroy rejections.
    • bootstrap(), internalCreateApplication(), and PlatformRef.bootstrapModule() settle cleanly with the destroyed ApplicationRef / NgModuleRef without bootstrapping root components when destroyed before or during initialization.
    • PendingTasks.run() checks DestroyRef.destroyed before reporting errors.
    • INTERNAL_APPLICATION_ERROR_HANDLER logs via console.error('ERROR', e) on the server when destroyed without a cached ErrorHandler instead of throwing from setTimeout.
  • @angular/common/http:
    • FetchBackend unsubscribes on DestroyRef.onDestroy to abort in-flight fetch calls and clear timeouts without emitting complete() or error(), cancels body streams on destroy, and skips initiating requests when already destroyed.
  • @angular/router:
    • Router.dispose() unsubscribes active setupNavigations transitions (after detaching the navigation event listener) and withEnabledBlockingInitialNavigation() skips starting navigation if the injector was destroyed while awaiting LOCATION_INITIALIZED.
  • @angular/platform-server:
    • renderInternal(), renderApplication(), and renderModule() return '' early when destroyed before or during async BEFORE_APP_SERIALIZED hooks, suppress post-destroy ErrorHandler reporting, and ensure asyncDestroyPlatform() always resolves safely.

Does this PR introduce a breaking change?

  • No

Other information

Companion @angular/ssr PR: angular/angular-cli#34768

Closes angular/angular-cli#34754

…nding tasks

When a server platform is destroyed while bootstrap or pending async work is in flight (for example, when an SSR request is aborted), several core paths could throw `NG0205` or rethrow errors via `setTimeout`, crashing the Node.js process:

- `ApplicationInitStatus`: unsubscribe observable initializers on `DestroyRef.onDestroy`, settle `donePromise` without marking `done = true`, stop remaining initializers if destroyed, and ignore late post-destroy rejections.
- `bootstrap()`, `internalCreateApplication()`, and `PlatformRef.bootstrapModule()`: return the destroyed `ApplicationRef` / `NgModuleRef` without looking up `ENABLE_ROOT_COMPONENT_BOOTSTRAP` or bootstrapping root components when destroyed before or during initialization.
- `PendingTasks.run()`: skip reporting rejections to `ErrorHandler` once `DestroyRef.destroyed` is true.
- `INTERNAL_APPLICATION_ERROR_HANDLER`: when destroyed on the server without a cached `ErrorHandler`, log via `console.error` instead of throwing asynchronously from `setTimeout`.
Register a `DestroyRef.onDestroy` teardown in `FetchBackend.handle()` that calls `observer.unsubscribe()` to abort in-flight `fetch` requests and clear timeouts without emitting `complete()` or `error()`. This avoids RxJS `EmptyError` rejections in `firstValueFrom` / `lastValueFrom` and unhandled rejections in unawaited async lifecycle hooks when an SSR platform is destroyed mid-request.

Also skip initiating `fetch` if `DestroyRef` is already destroyed, cancel unread or partially read response body streams after destruction, and remove the stray `observer.complete()` on stream cancellation.
Track the `navigationTransitions.setupNavigations(this)` subscription on `eventsSubscription` (after `subscribeToNavigationEvents()`) so `Router.dispose()` unsubscribes active navigation transitions and cancels in-flight guards, resolvers, and lazy loaders without dispatching events to a disposed router.

Also skip starting `initialNavigation()` in `withEnabledBlockingInitialNavigation()` if the injector was destroyed while awaiting `LOCATION_INITIALIZED`.
…r destruction

Return an empty string from `renderInternal()`, `renderApplication()`, and `renderModule()` when the platform or application is destroyed before or during async `BEFORE_APP_SERIALIZED` hooks, skip reporting post-destroy hook rejections to `ErrorHandler`, and ensure `asyncDestroyPlatform()` checks `platformRef.destroyed` and always resolves.
@pullapprove
pullapprove Bot requested a review from crisbeto November 20, 2026 07:43
@angular-robot angular-robot Bot added area: common/http Issues related to HTTP and HTTP Client area: core Issues related to the framework runtime area: server Issues related to server-side rendering area: router labels Nov 20, 2026
@ngbot ngbot Bot added this to the Backlog milestone Nov 20, 2026
@alan-agius4 alan-agius4 added the target: patch This PR is targeted for the next patch release label Nov 20, 2026
@alan-agius4
alan-agius4 requested review from JeanMeche and removed request for crisbeto November 20, 2026 07:46
@alan-agius4 alan-agius4 added the action: review The PR is still awaiting reviews from at least one requested reviewer label Nov 20, 2026
Comment thread packages/platform-server/src/utils.ts Resolved
Comment thread packages/common/http/src/fetch.ts Resolved
@pullapprove
pullapprove Bot requested review from atscott and kirjs November 20, 2026 14:28
@JeanMeche
JeanMeche requested review from thePunderWoman and removed request for kirjs November 21, 2026 12:31
Document that destroying the injector providing HttpClient (with the default
fetch backend) aborts in-flight requests without emitting complete or error,
so firstValueFrom/lastValueFrom promises stay unsettled and finally blocks do
not run. Recommend DestroyRef.onDestroy() or takeUntilDestroyed() when
cleaning up external resources such as locks or connections.
@angular-robot angular-robot Bot added the area: docs Related to the documentation label Nov 23, 2026
@alan-agius4 alan-agius4 reopened this Nov 23, 2026
@alan-agius4 alan-agius4 added the merge: caretaker note Alert the caretaker performing the merge to check the PR for an out of normal action needed or note label Nov 23, 2026
@alan-agius4

Copy link
Copy Markdown
Contributor Author

Caretaker note: g3 failure is pre-existing.

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: common/http Issues related to HTTP and HTTP Client area: core Issues related to the framework runtime area: docs Related to the documentation area: router area: server Issues related to server-side rendering merge: caretaker note Alert the caretaker performing the merge to check the PR for an out of normal action needed or note target: patch This PR is targeted for the next patch release

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Angular SSR can crash AngularAppEngine servers with a single aborted request (22.2.6 regression)

2 participants