Sub topic 10
Replaying user events captured before hydration
This chapter assumes you can read an Angular ApplicationConfig, you know what a template event binding such as (click) does, and you have SSR and hydration working from the earlier chapters. It covers one gap in that setup: what happens when a user interacts with server-rendered HTML before the browser has finished hydrating it.
The problem: a page that looks ready but is not
Server rendering sends finished HTML. The browser paints it right away, so the user sees buttons, forms, and menus. The JavaScript that attaches Angular's event listeners arrives later. It must download, parse, and run, and then hydration must walk the DOM and connect each component to its existing nodes.
Between first paint and the end of hydration, the page is visible but inert. A click in that window finds no Angular listener, so nothing happens. The user may click again, decide the site is broken, or submit a form half-filled. The window is short on a fast laptop and can last several seconds on a slow phone with a busy main thread.
Event replay closes this gap. Angular records the interactions that happen before hydration and runs your handlers afterward, so the click is not lost.
How event replay works
Event replay uses a small event-dispatch library that Angular ships. It has two parts.
- A tiny inline script in the server-rendered HTML. It runs before your application bundle loads. It registers listeners at the document root for common event types such as
clickandkeydown. When an event fires, the script finds the closest element that has an Angular listener in the template and puts the event in a queue. - The hydration runtime in the browser bundle. After an application or a part of it finishes hydrating, Angular takes the queued events and dispatches them to the listeners that now exist.
The listener at the document root works through event delegation. The browser bubbles the event up to the root, so the script does not need a separate handler on every element.
The inline script is part of the server-rendered response. It only exists if you enable event replay, so the feature costs a small amount of extra HTML on every SSR response.
Enabling event replay
Pass withEventReplay() to provideClientHydration. It goes in the shared application config, because the browser must know to consume the queue and the server must know to emit the script.
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient(withFetch()),
provideClientHydration(withEventReplay()),
],
};If you created your project with a recent Angular CLI and the --ssr option, this line is usually already present. Check app.config.ts before you add it. Adding a second provideClientHydration call is a mistake. Put all hydration features in one call.
What gets replayed
Replay depends on one thing: Angular can only replay an event if it can find a listener for it. That has practical consequences.
- Template listeners are covered. Bindings like
(click)="add()"or(keydown.enter)="submit()"are known to Angular from the compiled template, so the dispatch script can route events to them. - Events on elements with no Angular listener are ignored. Clicking plain text is not queued, because there is nothing to run later.
- Events are replayed in the order they happened. If a user clicks "Add" twice before hydration ends, the handler runs twice after it.
- Replay happens after hydration, not before. Your handler runs against the hydrated component, with its normal state and injected services.
One consequence is easy to miss. The event object was created at the real time of interaction. By replay time, the browser has already finished any default action for that event. Calling event.preventDefault() in a replayed handler cannot undo a default action that already ran. For links and form submissions, design the markup so that a native interaction before hydration is safe, and treat the replayed handler as a way to finish the work.
A component to test with
The component below counts clicks and records whether the click arrived through replay timing. It is a minimal way to see the feature work.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<button type="button" (click)="increment()">Clicked {{ count() }} times</button>
`,
})
export class CounterComponent {
protected count = signal(0);
protected increment(): void {
this.count.update((value) => value + 1);
}
}To observe replay, you need to click before hydration finishes. On a fast machine that is hard, so slow it down.
- Build and serve the SSR app with
ng buildfollowed bynode dist/<project>/server/server.mjs, or useng serveif your project is set up for SSR in development. - Open the page in Chrome DevTools. In the Performance tab settings, set CPU throttling to 6x slowdown. In the Network tab, choose a Slow 4G preset.
- Reload. As soon as the button appears, click it two or three times.
- When hydration finishes, the button text updates to match the number of clicks.
If the counter stays at 0 after hydration and your clicks happened early, check that withEventReplay() is present and that you are viewing the server-rendered build, not a client-only dev build.
Combining replay with incremental hydration
Event replay is also what makes incremental hydration feel correct. With incremental hydration, parts of the page stay dehydrated, meaning server-rendered but without listeners, until a trigger fires. A user can click inside such a block before its trigger has fired.
The hydrate on interaction trigger handles that case directly. The click starts hydration of the block, and replay delivers the same click to the freshly hydrated handler. The user does not need to click twice.
@defer (hydrate on interaction) {
<app-counter />
} @placeholder {
<p>Loading counter</p>
}For this to work, enable incremental hydration in the config. It builds on event replay, and Angular enables replay when you turn on incremental hydration.
import { provideClientHydration, withIncrementalHydration } from '@angular/platform-browser';
// Inside the providers array of appConfig:
provideClientHydration(withIncrementalHydration());The incremental hydration chapter covers all hydrate triggers. For this chapter, remember one point: replay is the mechanism that carries the triggering interaction into the block once it is hydrated.
You can also reproduce the pre-hydration window on purpose. A block with hydrate on timer(10s) stays dehydrated for ten seconds. A click inside it during that time is captured, hydration of the block is requested, and the handler runs. This gives you a repeatable test without network throttling.
@defer (hydrate on timer(10s)) {
<app-counter />
}Limits and failure modes
Event replay reduces the problem but does not remove it. Know where it stops.
| Situation | What happens | What to do |
|---|---|---|
| Hydration never completes because of an error | Queued events are never replayed | Fix the hydration error first. Check the console for mismatch messages. |
| Component is skipped with `ngSkipHydration` | Its DOM is discarded and rebuilt in the browser, so listeners are created fresh and earlier clicks are lost for that subtree | Avoid relying on early interaction in skipped components. |
| Event type is not captured by the dispatch script | The event is lost | Use the common event types in templates. Check the Angular documentation for the supported list in your version. |
| Handler depends on state that only exists after a long async load | Replay runs the handler when hydration ends, possibly before data arrives | Guard handlers against missing data, or disable the control until data is ready. |
| The user clicks, then navigates away before hydration finishes | Events for the old page are dropped with the page | No action needed. |
Replay can also surprise users. A click that seemed to do nothing for three seconds suddenly takes effect. If the action is destructive, such as "Delete" or "Pay", an unexpected late effect is worse than no effect. For such controls, consider rendering them disabled on the server and enabling them after hydration, using a signal set inside afterNextRender. The disabled attribute then prevents the click from being queued at all, because disabled buttons do not fire click events.
import { Component, afterNextRender, signal } from '@angular/core';
@Component({
selector: 'app-pay-button',
template: `
<button type="button" [disabled]="!ready()" (click)="pay()">Pay now</button>
`,
})
export class PayButtonComponent {
protected ready = signal(false);
constructor() {
afterNextRender(() => this.ready.set(true));
}
protected pay(): void {
console.log('Payment started');
}
}Verifying and debugging
When replay does not behave as expected, check these in order.
- Config. Confirm
withEventReplay()(orwithIncrementalHydration()) is inprovideClientHydrationin the config used by both server and browser. - Server output. View the page source, not the DOM in the Elements panel. Look for the inline script near the top of the document. If it is missing, the server build is not using the config you edited.
- Console. A hydration mismatch error means hydration for that part failed or fell back to a full re-render, which can drop queued events.
- Timing. Use CPU and network throttling so you can click inside the window. Without throttling, a pass proves little.
- Listener type. Confirm the handler is a template binding. If you attach a listener with
addEventListenerinside a lifecycle hook, replay will not know about it.
Exercise
A user clicks a button with (click)="save()" while the page is still hydrating. The app uses provideClientHydration() with no features. Another developer says "Angular will queue the click automatically." Is that right, and what single change makes it true?
Show answer
No. Without withEventReplay() the inline capture script is not emitted, so the early click finds no listener and is lost. Changing the call to provideClientHydration(withEventReplay()) in the shared application config makes Angular queue the click and run save() once hydration finishes.
Exercise
Why is it risky to rely on replay for a "Delete account" button, and what is a safer pattern?
Show answer
Replay runs the handler after hydration, which may be seconds after the user clicked. The user may no longer expect the action to happen. A safer pattern is to render the button disabled and enable it from a signal set in afterNextRender, so no click is queued before the app is interactive.
Exercise
You attach a listener with element.addEventListener('click', ...) inside afterNextRender. A user clicks the element before hydration. Will replay run that listener? Explain.
Show answer
No. The listener does not exist until afterNextRender runs in the browser, and replay routes events only to listeners that Angular knows from the compiled template. The early click is not delivered to it. Use a template binding such as (click) if the interaction must survive hydration.