diff --git a/CHANGELOG.md b/CHANGELOG.md index a1276c8..bb5b526 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to this project will be documented in this file. +## 2026-11-21 - version 1.4.11 + +- **fix: prerendered pages showed the time the site was built.** The menu bar clock rendered on the server, so every Thoughts page shipped a frozen build-time clock until the JavaScript loaded. The clock now renders empty on the server and starts in `afterNextRender`, which only runs in the browser +- **The menu bar hydrates.** It was marked `ngSkipHydration` to hide that server/browser difference, so the browser threw away the server's HTML for the whole bar and drew it again. With the difference gone, the attribute is gone. The interval also no longer starts from inside an `effect` with no signal dependencies +- **A spec renders the menu bar on the real server platform** (`menu-bar.server.spec.ts`, through `renderApplication`). TestBed runs browser-only hooks, so it can't show what the server sends +- **Angular guide, lesson 12: SSR and hydration** (`/thoughts/angular-12-ssr`). The live demo says whether the page you're reading was prerendered or rendered in your browser: the server writes its render time into `TransferState` and the browser reads it back. The lesson covers render modes per route, hydration, browser-only code, the HTTP transfer cache, event replay, incremental hydration and `PendingTasks` +- I formatted the demo's time with `DatePipe` first, and the initial bundle went to 407.07 kB, over the 400 kB budget. It's the lesson 03 trap again; `Intl.DateTimeFormat` brought it back to 395.26 kB + ## 2026-11-21 - version 1.4.10 - **fix: CI's typecheck checked zero files.** It ran `npx tsc --noEmit` against the root `tsconfig.json`, which has `"files": []` and only project references, so plain `tsc` compiled nothing and passed. It now typechecks `tsconfig.app.json` and `tsconfig.spec.json` diff --git a/package-lock.json b/package-lock.json index 5913851..84edbd0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "angular-paul", - "version": "1.4.10", + "version": "1.4.11", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "angular-paul", - "version": "1.4.10", + "version": "1.4.11", "dependencies": { "@angular/common": "^21.2.0", "@angular/compiler": "^21.2.0", diff --git a/package.json b/package.json index 1e171bf..ccdb7a8 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "angular-paul", - "version": "1.4.10", + "version": "1.4.11", "scripts": { "ng": "ng", "start": "ng serve", diff --git a/src/app/menu-bar/menu-bar.server.spec.ts b/src/app/menu-bar/menu-bar.server.spec.ts new file mode 100644 index 0000000..81e89b9 --- /dev/null +++ b/src/app/menu-bar/menu-bar.server.spec.ts @@ -0,0 +1,38 @@ +import { provideZonelessChangeDetection } from '@angular/core'; +import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser'; +import { provideServerRendering, renderApplication } from '@angular/platform-server'; +import { MenuBar } from './menu-bar'; + +// [ng-12 ssr] A server render through the real platform-server, not TestBed. +// TestBed runs every browser-only hook, so it can't show what the server emits: +// this is the HTML a visitor receives before any JavaScript has run. +async function renderMenuBarOnServer(): Promise { + const bootstrap = (context: BootstrapContext) => + bootstrapApplication( + MenuBar, + { providers: [provideZonelessChangeDetection(), provideServerRendering()] }, + context, + ); + return renderApplication(bootstrap, { + document: '', + url: '/', + }); +} + +describe('MenuBar server render', () => { + it('emits no clock time, so a prerendered page never shows the build time', async () => { + const html = await renderMenuBarOnServer(); + + const clock = html.match(/]*class="menu-bar-clock"[^>]*>([^<]*)<\/span>/); + expect(clock).not.toBeNull(); + expect(clock![1].trim(), 'server-rendered clock text').toBe(''); + }); + + it('lets the menu bar hydrate instead of being thrown away and re-rendered', async () => { + const html = await renderMenuBarOnServer(); + + const host = html.match(/]*>/); + expect(host).not.toBeNull(); + expect(host![0].toLowerCase()).not.toContain('ngskiphydration'); + }); +}); diff --git a/src/app/menu-bar/menu-bar.ts b/src/app/menu-bar/menu-bar.ts index c8e6de6..e478c86 100644 --- a/src/app/menu-bar/menu-bar.ts +++ b/src/app/menu-bar/menu-bar.ts @@ -1,14 +1,13 @@ -import { DOCUMENT, isPlatformBrowser } from '@angular/common'; +import { DOCUMENT } from '@angular/common'; import { + afterNextRender, ChangeDetectionStrategy, Component, computed, DestroyRef, - effect, ElementRef, inject, output, - PLATFORM_ID, signal, } from '@angular/core'; import { SettingsService } from '../shared/settings/settings.service'; @@ -19,22 +18,24 @@ import { MenuBarItem, MenuBarService } from './menu-bar.service'; changeDetection: ChangeDetectionStrategy.OnPush, templateUrl: './menu-bar.html', styleUrl: './menu-bar.scss', - // The live clock differs between server render and client bootstrap; skip - // hydration for this subtree so it re-renders cleanly in the browser. - host: { ngSkipHydration: 'true' }, }) export class MenuBar { private readonly menuBarService = inject(MenuBarService); private readonly host = inject>(ElementRef); private readonly document = inject(DOCUMENT); private readonly destroyRef = inject(DestroyRef); - private readonly platformId = inject(PLATFORM_ID); private readonly settings = inject(SettingsService); readonly menus = this.menuBarService.menus; readonly activeAppName = this.menuBarService.activeAppName; - private readonly now = signal(new Date()); - readonly clock = computed(() => this.formatTime(this.now())); + // [ng-12 ssr] null until the browser takes over. A prerendered page is built + // once and served for days, so any time the server wrote would be stale, and + // a server/client difference is what used to need ngSkipHydration here. + private readonly now = signal(null); + readonly clock = computed(() => { + const now = this.now(); + return now ? this.formatTime(now) : ''; + }); readonly openMenuId = signal(null); readonly spotlightRequested = output(); @@ -42,11 +43,12 @@ export class MenuBar { private outsideListener: (() => void) | null = null; constructor() { - effect(() => { - if (!isPlatformBrowser(this.platformId)) return; - this.intervalId = setInterval(() => { - this.now.set(new Date()); - }, 1000); + // [ng-12 ssr] afterNextRender never runs on the server, so it replaces the + // PLATFORM_ID check. It runs after hydration has claimed the server DOM, so + // filling the clock in here can't cause a mismatch. + afterNextRender(() => { + this.now.set(new Date()); + this.intervalId = setInterval(() => this.now.set(new Date()), 1000); }); this.destroyRef.onDestroy(() => { diff --git a/src/app/thoughts-content/lessons/lesson-12-ssr.spec.ts b/src/app/thoughts-content/lessons/lesson-12-ssr.spec.ts new file mode 100644 index 0000000..ac43aa0 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-12-ssr.spec.ts @@ -0,0 +1,72 @@ +import { PLATFORM_ID, TransferState } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import * as axeMatchers from 'vitest-axe/matchers'; +import { axe } from '../../../test/a11y'; +import { LESSON_PAGES } from './lessons'; +import { Lesson12Ssr, RENDERED_AT } from './lesson-12-ssr'; + +expect.extend(axeMatchers); + +describe('Lesson12Ssr', () => { + const origin = (fixture: ComponentFixture) => + (fixture.nativeElement as HTMLElement) + .querySelector('#demo-render-origin') + ?.textContent?.trim(); + + async function render(): Promise> { + const fixture = TestBed.createComponent(Lesson12Ssr); + await fixture.whenStable(); + return fixture; + } + + beforeEach(async () => { + await TestBed.configureTestingModule({ imports: [Lesson12Ssr] }).compileComponents(); + }); + + it('is registered as the lesson page for its thought', () => { + expect(LESSON_PAGES['angular-12-ssr']).toBeDefined(); + }); + + it('teaches at three levels, then pitfalls and interview questions', async () => { + const fixture = await render(); + const headings = [...(fixture.nativeElement as HTMLElement).querySelectorAll('h2')].map((h) => + h.textContent?.trim(), + ); + expect(headings).toEqual( + expect.arrayContaining([ + 'Simple', + 'Intermediate', + 'Expert', + 'Pitfalls', + 'Interview questions', + ]), + ); + }); + + it('stamps the render time into TransferState when it renders on the server', async () => { + TestBed.overrideProvider(PLATFORM_ID, { useValue: 'server' }); + await render(); + + expect(TestBed.inject(TransferState).get(RENDERED_AT, null)).toMatch(/^\d{4}-\d{2}-\d{2}T/); + }); + + it('reads the server stamp back in the browser instead of recomputing it', async () => { + TestBed.inject(TransferState).set(RENDERED_AT, '2026-11-21T09:05:00.000Z'); + const fixture = await render(); + + expect(origin(fixture)).toContain('Prerendered on the server'); + // Intl puts a narrow no-break space before AM on current ICU, so match any space. + expect(origin(fixture)).toMatch(/Nov 21, 2026, 9:05:00\sAM UTC/); + }); + + it('says so when there was no server render, as after a client-side navigation', async () => { + const fixture = await render(); + + expect(origin(fixture)).toContain('Rendered in your browser'); + }); + + it('has no axe violations', async () => { + const fixture = await render(); + expect(await axe(fixture.nativeElement)).toHaveNoViolations(); + }); +}); diff --git a/src/app/thoughts-content/lessons/lesson-12-ssr.ts b/src/app/thoughts-content/lessons/lesson-12-ssr.ts new file mode 100644 index 0000000..b079332 --- /dev/null +++ b/src/app/thoughts-content/lessons/lesson-12-ssr.ts @@ -0,0 +1,273 @@ +import { isPlatformServer } from '@angular/common'; +import { + ChangeDetectionStrategy, + Component, + inject, + makeStateKey, + PLATFORM_ID, + TransferState, +} from '@angular/core'; +import { Callout } from './callout'; +import { CodeBlock } from './code-block'; +import { InterviewQuestions } from './interview-questions'; +import { Lesson } from './lesson'; +import { LessonDemo } from './lesson-demo'; +import { LessonSection } from './lesson-section'; + +/** [ng-12 ssr] When the server rendered this page, as an ISO string. */ +export const RENDERED_AT = makeStateKey('lesson-12-rendered-at'); + +// Intl, not DatePipe: DatePipe's locale code lands in the initial bundle (lesson 03). +const UTC_DATE_TIME = new Intl.DateTimeFormat('en-US', { + dateStyle: 'medium', + timeStyle: 'medium', + timeZone: 'UTC', +}); + +@Component({ + selector: 'app-lesson-12-ssr', + changeDetection: ChangeDetectionStrategy.OnPush, + imports: [Lesson, LessonSection, LessonDemo, CodeBlock, Callout, InterviewQuestions], + template: ` + +

Simple

+

+ By default an Angular app is rendered in the browser (CSR): the server sends an empty + <app-root>, and nothing shows until the JavaScript has loaded and run. + Server-side rendering (SSR) runs the same components on the server and + sends finished HTML. Prerendering (SSG) does that once at build time and + saves the HTML as static files. +

+

+ Angular 21 picks the mode per route. On this site, the Thoughts pages are prerendered so + they load fast and search engines can read them. The desktop is client-rendered, because + it's interactive and has nothing worth indexing. +

+ +

+ Then the browser has to take over. Hydration means Angular adopts the DOM + the server sent, attaching listeners and state to it, instead of throwing it away and + rendering again. For that to work, the browser's first render has to match the server's. +

+ +

+ @if (renderedAt) { + Prerendered on the server at {{ renderedAt }} UTC, then hydrated in your browser. + } @else { + Rendered in your browser. You got here by navigating inside the app, so no server HTML + was involved. Reload the page to get the prerendered version. + } +

+
+

+ The time above is the build's, not yours. The server wrote it into + TransferState, a JSON blob embedded in the page. The browser reads it back + instead of computing its own, so both renders produce the same text. +

+ + +

Intermediate

+

+ Code that only works in a browser. Your components run in Node during SSR. + There is no window, localStorage or layout, and nothing should + keep a timer running. afterNextRender and afterEveryRender only + run in the browser, after the DOM exists. Put DOM measurement, third-party widgets and + timers there. +

+

+ This site's menu bar clock got this wrong. It started its interval inside an + effect behind an isPlatformBrowser check, rendered the time on the + server, and skipped hydration for the whole bar to hide the mismatch. Every prerendered page + showed the build time until the browser re-created the bar. +

+ +

+ HTTP during SSR. With hydration on, HttpClient caches GET and + HEAD responses made on the server in TransferState. The browser reuses them during hydration + instead of fetching the same data again. withHttpTransferCacheOptions() tunes + what gets cached. +

+

+ Event replay. withEventReplay() records clicks that land + before hydration finishes and replays them afterwards. The prerendered HTML carries the + markers for it. This is the "Run tests" button from lesson 11, as the build wrote it: +

+ + +

Expert

+

+ Incremental hydration. withIncrementalHydration() lets a + @defer block render on the server but stay dehydrated in the browser until + a trigger fires. Its JavaScript isn't even downloaded until then. The HTML is visible + immediately; it just isn't interactive yet. hydrate never keeps a static block + static forever. +

+ +

+ How the server knows it's done. It serialises the page when the app is + stable, which means no pending tasks. HttpClient and + resource() register pending tasks, so this lesson, loaded by a + resource() in the Thoughts reader, is in the prerendered HTML. Async work + Angular can't see, like a bare fetch() or setTimeout, needs + PendingTasks, or the server sends the page without it. +

+ +

+ ngSkipHydration on a host element makes Angular destroy that subtree's server + DOM and render it from scratch. It's an escape hatch for components that touch the DOM + directly. It doesn't fix a mismatch, it just stops reporting it, and you pay for rendering + twice. +

+
+ +

Pitfalls

+ +

+ A prerendered value is a build-time value. Clocks, "posted 3 minutes + ago", random ids and greetings by time of day are frozen into the HTML. A visitor can see + that HTML days later. Render them only in the browser, or transfer them. +

+
+ +

+ Server and browser disagree on time zones and locales. A build server + runs in UTC; your visitor doesn't. The demo above formats in UTC on purpose, so both sides + print the same string. It uses Intl.DateTimeFormat rather than + DatePipe: my first version used the pipe and the initial bundle grew 12 kB, + the same trap as lesson 03. +

+
+ +

+ Effects run on the server too. An effect is for syncing + state, not for browser setup. Starting a timer in one needs a platform guard, and + forgetting it leaves an interval running in the server process after the page has been + sent. +

+
+ +

+ Editing the DOM behind Angular's back. innerHTML, direct + appendChild or a jQuery plugin changes the structure hydration expects. + That's error NG0500, a hydration mismatch. Use template bindings, or + afterNextRender for DOM-only libraries. +

+
+ +

Interview questions

+ +
+ `, + styles: ` + .demo-render-origin { + margin: 0; + font-variant-numeric: tabular-nums; + } + `, +}) +export class Lesson12Ssr { + private readonly transferState = inject(TransferState); + + private readonly renderedAtIso = this.readRenderedAt(); + protected readonly renderedAt = this.renderedAtIso + ? UTC_DATE_TIME.format(new Date(this.renderedAtIso)) + : null; + + private readRenderedAt(): string | null { + // [ng-12 ssr] One of the few places PLATFORM_ID is still right: there is no + // server-only lifecycle hook to put this in. + if (isPlatformServer(inject(PLATFORM_ID))) { + const now = new Date().toISOString(); + this.transferState.set(RENDERED_AT, now); + return now; + } + const fromServer = this.transferState.get(RENDERED_AT, null); + // Remove it once read, so coming back later by navigation doesn't claim + // this view came from the server. + this.transferState.remove(RENDERED_AT); + return fromServer; + } + + protected readonly snippets = { + routes: `{ + path: 'thoughts/:slug', + renderMode: RenderMode.Prerender, + getPrerenderParams: async () => THOUGHTS.map((thought) => ({ slug: thought.slug })), +}, +// The interactive desktop shell is client-rendered — hybrid rendering by route. +{ + path: '**', + renderMode: RenderMode.Client, +},`, + transferState: `export const RENDERED_AT = makeStateKey('lesson-12-rendered-at'); + +private readRenderedAt(): string | null { + if (isPlatformServer(inject(PLATFORM_ID))) { + const now = new Date().toISOString(); + this.transferState.set(RENDERED_AT, now); + return now; + } + const fromServer = this.transferState.get(RENDERED_AT, null); + this.transferState.remove(RENDERED_AT); + return fromServer; +}`, + clock: `// Before: the server rendered a time, so the bar couldn't hydrate. +host: { ngSkipHydration: 'true' }, +private readonly now = signal(new Date()); +effect(() => { + if (!isPlatformBrowser(this.platformId)) return; + this.intervalId = setInterval(() => this.now.set(new Date()), 1000); +}); + +// After: the server renders no time, and the browser starts the clock. +private readonly now = signal(null); +readonly clock = computed(() => { + const now = this.now(); + return now ? this.formatTime(now) : ''; +}); +afterNextRender(() => { + this.now.set(new Date()); + this.intervalId = setInterval(() => this.now.set(new Date()), 1000); +});`, + jsaction: ``, + incremental: `@defer (hydrate on viewport) { + +} @placeholder { +

Comments

+} + +@defer (hydrate never) { + +}`, + }; + + protected readonly interview = [ + { + q: 'What is the difference between CSR, SSR and SSG?', + a: 'CSR renders in the browser: fast to serve, but nothing shows until the JavaScript runs, and crawlers see an empty shell. SSR renders on the server per request, so the HTML is complete and can depend on the request, at the cost of server time. SSG, or prerendering, renders once at build time and serves static files, which is the cheapest and fastest when content only changes on deploy. Angular 21 chooses per route with RenderMode.Client, Server and Prerender in the server routes.', + }, + { + q: 'What is hydration, and what breaks it?', + a: "Hydration is the browser adopting the server's DOM instead of re-creating it, so there's no flicker or lost scroll position. It needs the first client render to match the server's. It breaks when the two renders differ, for example a time, a random value or a locale, or when code changes the DOM outside Angular. Angular reports NG0500 for structural mismatches. ngSkipHydration opts a subtree out, but that's a workaround, not a fix.", + }, + { + q: 'How do you run code that needs the browser?', + a: 'afterNextRender for one-time setup and afterEveryRender for work after every render. Both only run in the browser, after the DOM exists. Inject DOCUMENT rather than touching the global, and provide browser APIs like localStorage through a token with a server fallback. isPlatformBrowser still exists, but render hooks are usually the better fit.', + }, + { + q: 'How do you avoid fetching data twice with SSR?', + a: "With hydration on, HttpClient's transfer cache stores GET and HEAD responses made on the server in TransferState, and the browser reuses them during hydration. For data that doesn't come through HttpClient, write it to TransferState yourself with makeStateKey on the server and read it in the browser.", + }, + { + q: 'What is incremental hydration?', + a: 'A @defer block with a hydrate trigger, such as hydrate on viewport, interaction or idle, renders fully on the server but stays dehydrated in the browser until the trigger fires, and its code is only downloaded then. Users see the content immediately while less JavaScript runs on load. hydrate never keeps static content static. It needs withIncrementalHydration() in provideClientHydration.', + }, + { + q: 'Tell me about an SSR bug you fixed.', + a: 'My site prerenders its blog pages, and every one of them shipped the menu bar clock as it was at build time. The bar was also marked ngSkipHydration, so the browser threw the server DOM away and rebuilt it. I made the clock render empty on the server, started it in afterNextRender, and removed ngSkipHydration so the bar hydrates. A spec renders the bar through the real server platform and asserts both.', + }, + ]; +} diff --git a/src/app/thoughts-content/lessons/lessons.ts b/src/app/thoughts-content/lessons/lessons.ts index 5357ceb..166ab89 100644 --- a/src/app/thoughts-content/lessons/lessons.ts +++ b/src/app/thoughts-content/lessons/lessons.ts @@ -23,4 +23,5 @@ export const LESSON_PAGES: Record Promise>> = { import('./lesson-09-change-detection').then((m) => m.Lesson09ChangeDetection), 'angular-10-directives': () => import('./lesson-10-directives').then((m) => m.Lesson10Directives), 'angular-11-testing': () => import('./lesson-11-testing').then((m) => m.Lesson11Testing), + 'angular-12-ssr': () => import('./lesson-12-ssr').then((m) => m.Lesson12Ssr), }; diff --git a/src/app/thoughts-content/thoughts-bodies.ts b/src/app/thoughts-content/thoughts-bodies.ts index 1396ff7..6f8e1c0 100644 --- a/src/app/thoughts-content/thoughts-bodies.ts +++ b/src/app/thoughts-content/thoughts-bodies.ts @@ -277,4 +277,8 @@ One gives every heading an id and registers it. The other watches those headings 'angular-11-testing': `I wrote a spec that reads this site's CI workflow, mostly as an example of a fitness test. It failed straight away. The typecheck step ran tsc against a root tsconfig that only holds project references, so it had been checking zero files while showing green. CI also never ran the production build, and no job had a time limit. Earlier in this series I had a test run print "426 passed" and then never exit, so that last one wasn't theoretical. The same lesson caught me out a second time. A test I wrote to pin a claim from lesson 09 passed when the claim said it shouldn't, and the claim turned out to be wrong. The demo below runs the real contact form validator's tests in the page, with a switch that puts back the bug lesson 08 fixed.`, + + 'angular-12-ssr': `Every Thoughts page on this site is prerendered at build time, and every one of them shipped the menu bar clock as it read during the build. Open a page a week later and the bar showed last week's time until the JavaScript loaded. The bar was also marked ngSkipHydration, so the browser threw away the HTML the server sent and drew the whole bar again. + +The fix was small once I could see what the server actually sends: the clock renders empty on the server, starts in afterNextRender, and the bar hydrates like everything else. A spec renders it through the real server platform to keep it that way. The demo below tells you whether the page you're reading came from the server or from your browser.`, }; diff --git a/src/app/thoughts-content/thoughts-data.ts b/src/app/thoughts-content/thoughts-data.ts index 8ef4ccd..fe14339 100644 --- a/src/app/thoughts-content/thoughts-data.ts +++ b/src/app/thoughts-content/thoughts-data.ts @@ -287,4 +287,13 @@ export const THOUGHTS: ThoughtEntry[] = [ tags: ['angular-guide', 'testing', 'angular'], relatedApp: 'contact', }, + { + slug: 'angular-12-ssr', + title: 'Angular 12: SSR and hydration', + date: '2026-11-21', + summary: + 'Render modes per route, hydration, TransferState, browser-only code, event replay and incremental hydration. Built while stopping every prerendered page from showing the time the site was built.', + tags: ['angular-guide', 'ssr', 'angular'], + relatedApp: 'readme', + }, ];