SEO & metadata

Search engines reward HTML that already says what a page is, and because this app is server-rendered, every crawler gets a complete document on the first response, not an empty shell waiting for JavaScript. The sections below set a real per-route title, a full set of meta tags, structured data, and a canonical URL. Then they read those values back out of the live document, so you can see exactly what shipped.

Per-route <title> & meta tags

Why it matters: the title is the single biggest on-page signal and the clickable headline in results; the description and Open Graph / Twitter tags decide how a link looks when it's shared. Setting them per route (through Angular's Title and Meta services, so they render on the server) means each page presents itself correctly instead of inheriting a generic site-wide default. This panel reads the values straight back from the DOM, so it shows what was actually set, not what it was meant to set.

Metadata values read back from the document
TagSourceLive value
Titledocument.titleSEO & metadata · Enterprise Angular Showcase | Miguel Carino
Descriptionmeta[name=description]How a server-rendered Angular app earns its place in search: per-route titles and meta tags, JSON-LD structured data, canonical URLs, and the sitemap/robots story.
og:titlemeta[property=og:title]SEO & metadata · Enterprise Angular Showcase | Miguel Carino
og:typemeta[property=og:type]website
og:urlmeta[property=og:url]https://demo.miguelcarino.com/seo
twitter:cardmeta[name=twitter:card]summary_large_image
View source: the app-wide MetadataStrategymetadata.strategy.ts

This page sets its tags by hand to make the mechanism visible, but the app doesn't repeat that per route. A single TitleStrategy runs on every navigation: it composes the title from the route's title, reads the description off the leaf route's data, and writes the description, Open Graph / Twitter, robots and canonical tags, all through the SSR-safe Title/Meta services so they land in the first HTML response.

ts
import { DOCUMENT } from '@angular/common';
import { Injectable, inject } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { type RouterStateSnapshot, TitleStrategy } from '@angular/router';

// The production origin: canonical URLs and Open Graph tags point here.
const SITE_ORIGIN = 'https://demo.miguelcarino.com';
const SITE_NAME = 'Enterprise Angular Showcase';
const AUTHOR = 'Miguel Carino';
/*
 * Used when a route has no `data.description`. Without it the previous page's tags would stay
 * in the head after a client-side navigation, describing a page you've left.
 */
export const SITE_DESCRIPTION =
  'Enterprise Angular patterns, accessibility, performance and micro-frontends, all original, all running.';

/*
 * A `TitleStrategy` that does the whole per-route metadata job on every navigation: the
 * document title (from the route's `title`), the meta description, the canonical URL, and
 * Open Graph / Twitter card tags (from the route's `data.description`, or the site default). The /seo page
 * demonstrates the technique in isolation; this applies it app-wide so every route a blog
 * post links is correct in a tab and shares cleanly as a preview card.
 *
 * SSR-safe: `Title`/`Meta` render into the prerendered head on the server, and the canonical
 * link is written through `DOCUMENT` (which Angular provides server-side too), so the tags
 * are present in the static HTML, not only after hydration.
 */
@Injectable({ providedIn: 'root' })
export class MetadataStrategy extends TitleStrategy {
  private readonly title = inject(Title);
  private readonly meta = inject(Meta);
  private readonly document = inject(DOCUMENT);

  override updateTitle(snapshot: RouterStateSnapshot): void {
    /*
     * Compose the full document title from the route's page name and the site brand, so every
     * tab and search result reads "<Page> · Enterprise Angular Showcase | Miguel Carino".
     */
    const page = this.buildTitle(snapshot);
    const title = page ? `${page} · ${SITE_NAME} | ${AUTHOR}` : `${SITE_NAME} | ${AUTHOR}`;
    this.title.setTitle(title);

    const description =
      (this.deepestData(snapshot)['description'] as string | undefined) ?? SITE_DESCRIPTION;
    const url = `${SITE_ORIGIN}${snapshot.url.split(/[?#]/)[0]}`;

    this.meta.updateTag({ name: 'description', content: description });
    this.meta.updateTag({ property: 'og:description', content: description });
    this.meta.updateTag({ name: 'twitter:description', content: description });
    this.meta.updateTag({ property: 'og:title', content: title });
    this.meta.updateTag({ property: 'og:type', content: 'website' });
    this.meta.updateTag({ property: 'og:site_name', content: SITE_NAME });
    this.meta.updateTag({ property: 'og:url', content: url });
    this.meta.updateTag({ name: 'twitter:card', content: 'summary_large_image' });
    this.meta.updateTag({ name: 'twitter:title', content: title });
    /*
     * Every demo route is unique interactive content meant to be found, so the whole of demo.
     * is index,follow. The thin surfaces (the federated remotes, Storybook) opt out on their own.
     */
    this.meta.updateTag({ name: 'robots', content: 'index, follow' });

    this.setCanonical(url);
  }

  // The metadata lives on the leaf route, so walk to the deepest activated snapshot.
  private deepestData(snapshot: RouterStateSnapshot): Record<string, unknown> {
    let route = snapshot.root;
    while (route.firstChild) {
      route = route.firstChild;
    }
    return route.data;
  }

  private setCanonical(url: string): void {
    const head = this.document.head;
    if (!head) {
      return;
    }
    let link = head.querySelector<HTMLLinkElement>('link[rel="canonical"]');
    if (!link) {
      link = this.document.createElement('link');
      link.setAttribute('rel', 'canonical');
      head.appendChild(link);
    }
    link.setAttribute('href', url);
  }
}

JSON-LD structured data

Why it matters: structured data lets you describe the page in a vocabulary search engines understand (schema.org), which is what powers rich results: breadcrumbs, sitelinks, knowledge panels. The page injects a <script type="application/ld+json"> into the document head holding a small graph (WebSite, WebPage, and a BreadcrumbList), and removes it again on destroy so it never leaks into the next route. Here is the exact JSON that was emitted:

{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "WebSite",
      "name": "Enterprise Angular Showcase by Miguel Carino",
      "url": "https://demo.miguelcarino.com"
    },
    {
      "@type": "WebPage",
      "name": "SEO & metadata · Enterprise Angular Showcase | Miguel Carino",
      "description": "How a server-rendered Angular app earns its place in search: per-route titles and meta tags, JSON-LD structured data, canonical URLs, and the sitemap/robots story.",
      "url": "https://demo.miguelcarino.com/seo",
      "isPartOf": {
        "@type": "WebSite",
        "url": "https://demo.miguelcarino.com"
      }
    },
    {
      "@type": "BreadcrumbList",
      "itemListElement": [
        {
          "@type": "ListItem",
          "position": 1,
          "name": "Home",
          "item": "https://demo.miguelcarino.com"
        },
        {
          "@type": "ListItem",
          "position": 2,
          "name": "SEO & Metadata",
          "item": "https://demo.miguelcarino.com/seo"
        }
      ]
    }
  ]
}
View source: where this page injects its JSON-LD and canonicalseo.ts

injectJsonLd() writes the script tag into the head and ngOnDestroy removes it, so the graph never leaks into the next route. setCanonical() queries before it adds, so re-entering the route updates the tag in place.

ts
import { DOCUMENT, isPlatformBrowser } from '@angular/common';
import {
  ChangeDetectionStrategy,
  Component,
  type OnDestroy,
  type OnInit,
  PLATFORM_ID,
  inject,
  signal,
} from '@angular/core';
import { Meta, type MetaDefinition, Title } from '@angular/platform-browser';
import { RouterLink } from '@angular/router';
import { Alert, Badge, Button, SourceViewer } from '@foo/ui';
import { appConfig } from '../../shared/snippets/appConfig.generated';
import { metadataStrategy } from '../../shared/snippets/metadataStrategy.generated';
import { seoPage } from '../../shared/snippets/seoPage.generated';
import { serverConfig } from '../../shared/snippets/serverConfig.generated';
import { serverRoutes } from '../../shared/snippets/serverRoutes.generated';

// Marks the page's JSON-LD script so a later pass can find it again.
const SEO_JSON_LD_ID = 'seo-page-json-ld';

interface MetaReadback {
  readonly label: string;
  readonly source: string;
  readonly value: string;
}

/*
 * The SEO & metadata section. Because the dashboard is server-rendered and then hydrated,
 * everything a crawler needs is in the first HTML response, with no "wait for JS" gap.
 * This page makes that machinery visible: on init it sets a real page title and a full set
 * of `description`/Open Graph/Twitter meta tags, injects JSON-LD structured data and a
 * canonical link into the document head, then reads those same values *back out of the DOM*
 * so you can see the effect rather than take it on faith. Every head mutation is guarded so
 * it is safe during prerender and in jsdom, and is unwound on destroy so the tags don't leak
 * into the next route.
 */
@Component({
  selector: 'foo-seo',
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [Alert, Badge, Button, RouterLink, SourceViewer],
  templateUrl: './seo.html',
  styleUrl: './seo.scss',
})
export class Seo implements OnInit, OnDestroy {
  private readonly title = inject(Title);
  private readonly meta = inject(Meta);
  private readonly document = inject(DOCUMENT);
  private readonly isBrowser = isPlatformBrowser(inject(PLATFORM_ID));

  // A stable, canonical-looking origin for the demo. In a real app this comes from config.
  private readonly origin = 'https://demo.miguelcarino.com';
  private readonly path = '/seo';

  private readonly pageTitle = 'SEO & metadata · Enterprise Angular Showcase | Miguel Carino';
  private readonly pageDescription =
    'How a server-rendered Angular app earns its place in search: per-route titles and ' +
    'meta tags, JSON-LD structured data, canonical URLs, and the sitemap/robots story.';

  // Elements we add to <head> ourselves, tracked so we can remove exactly them on destroy.
  private jsonLdScript: HTMLScriptElement | null = null;
  private canonicalLink: HTMLLinkElement | null = null;

  // The live values, read back from the DOM after we set them, for the read-back panel.
  protected readonly metaReadback = signal<readonly MetaReadback[]>([]);
  protected readonly canonicalReadback = signal<string>('');
  protected readonly jsonLd = signal<string>('');

  ngOnInit(): void {
    this.title.setTitle(this.pageTitle);
    this.setMetaTags();
    this.setCanonical();
    this.injectJsonLd();
    this.readBack();
  }

  ngOnDestroy(): void {
    // Leave the document as we found it: these tags belong to this route only.
    this.jsonLdScript?.remove();
    this.canonicalLink?.remove();
    this.jsonLdScript = null;
    this.canonicalLink = null;
  }

  // Sets description + Open Graph + Twitter Card tags via Angular's SSR-safe Meta service.
  private setMetaTags(): void {
    const url = `${this.origin}${this.path}`;
    const tags: Record<string, string> = {
      description: this.pageDescription,
      'og:type': 'website',
      'og:title': this.pageTitle,
      'og:description': this.pageDescription,
      'og:url': url,
      'twitter:card': 'summary_large_image',
      'twitter:title': this.pageTitle,
      'twitter:description': this.pageDescription,
    };

    for (const [key, content] of Object.entries(tags)) {
      // `name` for standard/Twitter tags, `property` for the og: namespace.
      const selector = key.startsWith('og:') ? `property='${key}'` : `name='${key}'`;
      const attr: MetaDefinition = key.startsWith('og:')
        ? { property: key, content }
        : { name: key, content };
      // updateTag is idempotent, so re-visiting the route overwrites rather than duplicates.
      this.meta.updateTag(attr, selector);
    }
  }

  // Reads the tags back out of the live document so the panel reflects reality, not intent.
  private readBack(): void {
    const get = (selector: string): string => this.meta.getTag(selector)?.content ?? '(unset)';

    this.metaReadback.set([
      { label: 'Title', source: 'document.title', value: this.document.title || '(unset)' },
      { label: 'Description', source: 'meta[name=description]', value: get("name='description'") },
      { label: 'og:title', source: 'meta[property=og:title]', value: get("property='og:title'") },
      { label: 'og:type', source: 'meta[property=og:type]', value: get("property='og:type'") },
      { label: 'og:url', source: 'meta[property=og:url]', value: get("property='og:url'") },
      {
        label: 'twitter:card',
        source: 'meta[name=twitter:card]',
        value: get("name='twitter:card'"),
      },
    ]);

    this.canonicalReadback.set(this.canonicalLink?.href || '(unset)');
  }

  /*
   * Creates or updates `<link rel="canonical">`. We query first so navigating back to this
   * route reuses the existing element instead of stacking duplicates in the head.
   */
  private setCanonical(): void {
    const head = this.document.head;
    if (!head) {
      return;
    }
    const href = `${this.origin}${this.path}`;
    let link = head.querySelector<HTMLLinkElement>("link[rel='canonical']");
    if (!link) {
      link = this.document.createElement('link');
      link.setAttribute('rel', 'canonical');
      head.appendChild(link);
    }
    link.setAttribute('href', href);
    this.canonicalLink = link;
  }

  // Builds a small graph of structured data and injects it as a JSON-LD script.
  private injectJsonLd(): void {
    const head = this.document.head;
    if (!head) {
      return;
    }
    const url = `${this.origin}${this.path}`;
    const graph = {
      '@context': 'https://schema.org',
      '@graph': [
        {
          '@type': 'WebSite',
          name: 'Enterprise Angular Showcase by Miguel Carino',
          url: this.origin,
        },
        {
          '@type': 'WebPage',
          name: this.pageTitle,
          description: this.pageDescription,
          url,
          isPartOf: { '@type': 'WebSite', url: this.origin },
        },
        {
          '@type': 'BreadcrumbList',
          itemListElement: [
            { '@type': 'ListItem', position: 1, name: 'Home', item: this.origin },
            { '@type': 'ListItem', position: 2, name: 'SEO & Metadata', item: url },
          ],
        },
      ],
    };

    const json = JSON.stringify(graph, null, 2);
    /*
     * The prerendered head already holds this script, and hydration only adopts the app's own
     * DOM, not the head. Reuse it by id, or the browser adds a second copy and ngOnDestroy
     * removes only that one, leaving the server's behind on the next route.
     */
    let script = head.querySelector<HTMLScriptElement>(`script#${SEO_JSON_LD_ID}`);
    if (!script) {
      script = this.document.createElement('script');
      script.id = SEO_JSON_LD_ID;
      script.setAttribute('type', 'application/ld+json');
      head.appendChild(script);
    }
    // textContent, never innerHTML: the payload is data, not markup.
    script.textContent = json;

    this.jsonLdScript = script;
    this.jsonLd.set(json);
  }

  // Surfaced in the template so the "why SSR" note can state where this rendered.
  protected readonly renderedOn = this.isBrowser ? 'the browser (after hydration)' : 'the server';

  // Illustrative robots.txt for a production origin: allow all, point at the sitemap.
  protected readonly robotsProd = [
    'User-agent: *',
    'Allow: /',
    '',
    `Sitemap: ${this.origin}/sitemap.xml`,
  ].join('\n');

  // The staging counterpart: block everything so a non-prod build can't be indexed.
  protected readonly robotsStaging = ['User-agent: *', 'Disallow: /'].join('\n');

  // The real app-wide TitleStrategy this page demonstrates in isolation.
  protected readonly metadataStrategySrc = metadataStrategy;
  protected readonly seoPageSrc = seoPage;
  protected readonly ssrSources = [serverRoutes, serverConfig];
  protected readonly appConfigSrc = appConfig;

  /*
   * The event replay demo. The button is in the prerendered HTML before any script runs, so a
   * click can land before hydration; the e2e spec holds main.js back to prove that click counts.
   */
  protected readonly clicks = signal(0);

  protected countClick(): void {
    this.clicks.update((n) => n + 1);
  }
}

Canonical URL

Why it matters: the same content is often reachable at several URLs: tracking params, trailing slashes, http vs https, paginated variants. Left alone, a crawler treats those as duplicates and splits ranking signals across them. A <link rel="canonical"> names the one URL that should be indexed, so all the authority consolidates there. The page queries for an existing tag before adding one, so re-entering the route updates it in place rather than stacking duplicates.

link[rel=canonical] →https://demo.miguelcarino.com/seo

The code is in the source panel under JSON-LD above. On every other route the canonical comes from the app-wide MetadataStrategy, shown under the first section.

Sitemap & robots

Why it matters: robots.txt and sitemap.xml are how you tell crawlers what to look at and what to ignore. In an SSR Angular app these are best served as real routes (or static files) at the origin root. A server handler can generate sitemap.xml from the same route table the app already owns, so the map can never drift from what actually ships.

User-agent: *
Allow: /

Sitemap: https://demo.miguelcarino.com/sitemap.xml

The staging trap to avoid: a non-production build that a crawler reaches will compete with your real site. The fix is to flip a flag by environment: emit a blanket noindex everywhere a build is not production:

User-agent: *
Disallow: /

Per-page, the same intent is expressed with <meta name="robots" content="noindex, nofollow">, which, because it is server-rendered, is present in the very first response a crawler sees.

Why SSR is the foundation

Everything above only works because the HTML is real
A client-only SPA ships an empty shell and fills it in after the JavaScript runs; a crawler that doesn't wait sees nothing. This app prerenders every route to static HTML at build time, then hydrates it in the browser, so the title, meta, JSON-LD and canonical link are all in the first byte of HTML, no execution required. SSR isn't an SEO feature you add on top; it's the layer that makes every other signal on this page trustworthy. This view rendered on the server.
View source

app.routes.server.ts prerenders every route (the '**' wildcard picks up new ones automatically); app.config.server.ts merges in the server rendering providers. The build writes one HTML file per route, which is what gets deployed.

ts
import { RenderMode, ServerRoute } from '@angular/ssr';

/*
 * Prerender EVERY route to its own static HTML. Each demo page ships with its own <title>,
 * canonical, OG/Twitter tags, and JSON-LD baked in (set by core/metadata.strategy.ts during the
 * render), so a crawler or a no-JS fetch of /accessibility gets that page, not the Overview shell.
 *
 * The wildcard is deliberate over a hand-listed route table: Angular discovers every statically
 * reachable route from app.routes.ts and prerenders each (see dist/apps/dashboard/prerendered-
 * routes.json: every route but the one below, including the other fundamentals sub-routes). A new route is covered automatically;
 * an explicit list would silently miss whatever someone forgot to add to it.
 *
 * NB the delivery side must cooperate: the per-route index.html only reaches the browser if the host
 * serves real directories instead of rewriting them to the root shell (see the `!-d` guard in the
 * SPA .htaccess, scripts/package-deploy-zips.mjs).
 */
export const serverRoutes: ServerRoute[] = [
  /*
   * The one exception: /fundamentals/admin sits behind a canMatch on the visitor's demo role, which
   * only exists in their browser. At build time the guard says no, nothing matches, and there's no
   * page to write, so it renders on the client, where the guard can actually decide.
   */
  {
    path: 'fundamentals/admin',
    renderMode: RenderMode.Client,
  },
  {
    path: '**',
    renderMode: RenderMode.Prerender,
  },
];

Hydration and event replay

The browser half is one line in app.config.ts: provideClientHydration(withEventReplay(), withIncrementalHydration()).

  • provideClientHydration() keeps the server's DOM and attaches to it, instead of throwing it away and rendering the page again. The server marks each component's host with an ngh attribute and writes the matching node data into a <script id="ng-state"> transfer script; that is how the client knows which node is which. It also turns on the HttpClient transfer cache, so a request the server already made is not sent again on load.
  • withEventReplay() inlines a small script in the server HTML that records the clicks (and other events the page listens for) made while the app's JavaScript is still loading. Once the app has hydrated, Angular replays them to the real handlers, so an early click is not lost.
  • withIncrementalHydration() lets a @defer (hydrate on …) block stay dehydrated until its trigger fires (see incremental hydration on the Performance page). Since Angular 22 this is on by default with provideClientHydration() and the function is deprecated, so the call here only states the intent. It brings event replay in too, because a dehydrated block needs it.

Clicks counted: 0

On a slow connection you can press the button before the page has hydrated, and the click still counts. The end-to-end test proves it: it holds back the app's JavaScript, clicks, sees the count still at 0, then lets the script load and watches the count reach 1.

View source: the client hydration providersapp.config.ts

provideClientHydration(withEventReplay(), withIncrementalHydration()) is the hydration line; the rest of the file is the app's other root providers.

ts
import {
  ApplicationConfig,
  provideBrowserGlobalErrorListeners,
  provideZonelessChangeDetection,
} from '@angular/core';
import { provideRouter, TitleStrategy, withInMemoryScrolling } from '@angular/router';
import {
  provideClientHydration,
  withEventReplay,
  withIncrementalHydration,
} from '@angular/platform-browser';
import { provideNoopAnimations } from '@angular/platform-browser/animations';
import { HttpBackend, provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideStore } from '@ngrx/store';
import { provideEffects } from '@ngrx/effects';
import { appRoutes } from './app.routes';
import { MetadataStrategy } from './core/metadata.strategy';
import {
  authInterceptor,
  FakeBackend,
  retryAndMapErrorsInterceptor,
} from './pages/fundamentals/examples/http-demo';
import {
  VALIDATION_RULES,
  maxLengthRule,
  nonEmptyRule,
} from './pages/fundamentals/examples/feature-flags';

export const appConfig: ApplicationConfig = {
  providers: [
    /*
     * The app runs without zone.js. CD is driven by signals, OnPush, and the async pipe, never
     * by a zone patching the event loop. zone.js is never loaded; this makes that stance explicit
     * (and matches the StackBlitz demos + the Testing page's zoneless claim).
     */
    provideZonelessChangeDetection(),
    provideClientHydration(withEventReplay(), withIncrementalHydration()),
    provideBrowserGlobalErrorListeners(),
    /*
     * Navigating to a new route resets the scroll to the top. Without this the next page opens
     * at the previous page's scroll offset (jarring, and worse from the mobile drawer). A URL that
     * carries a #fragment is the exception: anchorScrolling jumps to that section instead, so
     * deep/bookmarked links still land where they point. The sticky-header offset is set in app.ts.
     */
    provideRouter(
      appRoutes,
      withInMemoryScrolling({ scrollPositionRestoration: 'enabled', anchorScrolling: 'enabled' }),
    ),
    /*
     * App-wide per-route metadata: sets title, description, canonical, and OG/Twitter tags
     * from each route's `data` on every navigation (see core/metadata.strategy.ts).
     */
    { provide: TitleStrategy, useClass: MetadataStrategy },
    /*
     * Angular Material (used on the Material & CDK page) emits synthetic animation
     * properties; the no-op provider satisfies them without animation machinery, which
     * keeps it SSR- and zoneless-safe. Other pages use no Material, so this is inert there.
     */
    provideNoopAnimations(),
    /*
     * Empty root Store + effects runner. Feature slices register themselves lazily via
     * `provideState`/`provideEffects` on the pages that use them (see the classic-NgRx page).
     */
    provideStore(),
    provideEffects(),
    /*
     * HttpClient for the Fundamentals HTTP demo. The interceptor chain is what it teaches: auth
     * stamps the header on the way out (outermost), then retry/error-mapping wraps the request.
     * Below them all, a FakeBackend stands in for the server that answers /api/quotes, provided
     * as the HttpBackend so it's the request's true producer and retry can resubscribe it. There's
     * no real endpoint (the app's data is synthetic), and this is inert for pages that make no
     * request.
     */
    provideHttpClient(withInterceptors([authInterceptor, retryAndMapErrorsInterceptor])),
    { provide: HttpBackend, useClass: FakeBackend },
    /*
     * Two validation rules contributed into the multi-provider token the Fundamentals DI demo
     * reads. `multi: true` means each provider adds to the array rather than replacing it: the
     * same mechanism behind HTTP_INTERCEPTORS, shown small.
     */
    { provide: VALIDATION_RULES, useValue: nonEmptyRule, multi: true },
    { provide: VALIDATION_RULES, useValue: maxLengthRule, multi: true },
  ],
};