DEV Community

Cover image for Managing TanStack Start/Router Head Tags Without Duplicate Canonicals
Saiful Islam
Saiful Islam

Posted on Edited on

Managing TanStack Start/Router Head Tags Without Duplicate Canonicals

A small head factory that kills duplicated canonical links and stale social tags — and the surprising part is that the URL must be stamped by the route, not the root.

The Problem

The root head gives every page a title, description, and canonical. The about page adds its own title and Open Graph tags. Both look correct alone.

// src/routes/__root.tsx
export const Route = createRootRoute({
  head: () => ({
    meta: [
      { title: "Atlas" },
      { name: "description", content: "Field notes for hikers" },
      { property: "og:title", content: "Atlas" },
      { property: "og:url", content: "https://atlas.test" },
    ],
    links: [{ rel: "canonical", href: "https://atlas.test" }],
  }),
});
Enter fullscreen mode Exit fullscreen mode
// src/routes/about.tsx
export const Route = createFileRoute("/about")({
  head: () => ({
    meta: [
      { title: "About | Atlas" },
      { property: "og:title", content: "About | Atlas" },
      { property: "og:url", content: "https://atlas.test/about" },
    ],
    links: [{ rel: "canonical", href: "https://atlas.test/about" }],
  }),
});
Enter fullscreen mode Exit fullscreen mode

What ships:

<head>
  <title>About | Atlas</title>
  <meta property="og:title" content="About | Atlas">
  <meta property="og:url" content="https://atlas.test/about">
  <link rel="canonical" href="https://atlas.test">
  <link rel="canonical" href="https://atlas.test/about">
</head>
Enter fullscreen mode Exit fullscreen mode

TanStack Router dedupes title and meta by last nested occurrence, but not links. Two canonical links survive, and crawlers get conflicting answers about the authoritative URL.

Fix one: compute the canonical in the root from the browser location.

links: [{ rel: "canonical", href: `https://atlas.test${window.location.pathname}` }],
Enter fullscreen mode Exit fullscreen mode

It works in the browser but not during SSR, where window does not exist. Crawlers get no reliable canonical.

Fix two: delete the root canonical and put one in every leaf route.

// root
links: []; // the canonical lives in each route now
Enter fullscreen mode Exit fullscreen mode

Routes without a head get none; a nested route that adds one recreates the duplicate.

Fix three: keep the leaf route but build the URL by concatenation.

head: ({ match }) => ({
  links: [{ rel: "canonical", href: `https://atlas.test/${match.pathname}` }],
});
Enter fullscreen mode Exit fullscreen mode

match.pathname already starts with /, so you get https://atlas.test//about; a trailing slash gives the page a second URL.

You need one canonical identity per URL, present everywhere, but only the leaf route knows the path and only the root knows the site.

A head factory closes over site facts once and takes page facts as arguments:

export function buildHead(config: BuildHeadConfig) {
  const ctx = createHeadContext(config);
  const urlFor = (path: string) => createCanonicalUrl(ctx.baseUrl, path);
  return {
    globalHead: () => ({
      meta: buildHeadMeta(ctx, {
        title: ctx.defaultTitle,
        description: ctx.defaultDescription,
        url: urlFor("/"),
      }),
      links: buildHeadLinks(ctx.stylesheets),
    }),
    head: (options: HeadPageOptions) => {
      const url = urlFor(options.pathname);
      return {
        meta: buildHeadMeta(ctx, {
          title: resolveTitle(ctx.titleTemplate, options),
          description: options.description ?? ctx.defaultDescription,
          url,
        }),
        links: [...buildHeadLinks(ctx.stylesheets, url), ...buildAlternateLinks(url)],
      };
    },
  };
}
Enter fullscreen mode Exit fullscreen mode

The Mental Model

Treat the module as a printing press with two plates: a master plate for site facts, a page plate for path and title. It prints one sheet; <HeadContent /> hands it to the browser.

  • Identity: buildHead(config) sets the press once. Normalized base URL, title template, robots, theme color, OG image, and stylesheets live in a closure for the life of the app.
  • Update timing: each route match calls head() with a pathname and title. The press prints a fresh sheet at match time. No effect, state, or subscription schedules the work.
  • Read timing: <HeadContent /> reads the sheets for the matched route tree during SSR and again on client navigation. The router merges them; leaf meta entries win by name or property.

Server and client print the same sheet because nothing reads the DOM. A new config means a new press; you cannot reconfigure one mid-flight.

The press stamps the address once, on the sheet that actually goes out.

How to Use It

Setup

src/
├── lib/
│   ├── head/
│   │   ├── buildHead.ts
│   │   ├── index.ts
│   │   ├── links.ts
│   │   ├── meta.ts
│   │   ├── og.ts
│   │   ├── types.ts
│   │   └── url.ts
│   └── site-config.ts
├── routes/
│   ├── __root.tsx
│   └── about.tsx
└── utils/
    └── url.ts
Enter fullscreen mode Exit fullscreen mode

A minimal generic stand-in for config values your app already has. Replace the strings with your own.

// src/lib/site-config.ts
export const siteConfig = {
  appName: "Atlas",
  siteUrl: "https://atlas.test",
  defaultTitle: "Atlas",
  titleTemplate: "%s | Atlas",
  defaultDescription: "Field notes for hikers",
  themeColor: "#0f172a",
  robots: "index, follow",
  social: true,
  stylesheets: ["/styles.css"],
  ogImagePath: "/opengraph-image.jpg",
};
Enter fullscreen mode Exit fullscreen mode

The two URL normalizers:

// src/utils/url.ts
export function normalizeUrl(urlValue: string): string {
  return urlValue.replace(/\/+$/, "");
}

export function normalizePathname(pathname: string): string {
  const trimmed = pathname.replace(/^\/+|\/+$/g, "").replace(/\/{2,}/g, "/");

  return trimmed === "" ? "/" : `/${trimmed}`;
}
Enter fullscreen mode Exit fullscreen mode

Every type used below:

// src/lib/head/types.ts
export interface HeadMeta {
  charSet?: string;
  name?: string;
  property?: string;
  content?: string;
  title?: string;
}

export interface HeadLink {
  rel: string;
  href?: string;
  hrefLang?: string;
  type?: string;
  sizes?: string;
}

export interface HeadResult {
  meta: HeadMeta[];
  links: HeadLink[];
}

export interface BuildHeadConfig {
  appName: string;
  siteUrl: string;
  defaultTitle: string;
  titleTemplate: string;
  defaultDescription: string;
  themeColor: string;
  robots?: string;
  stylesheets?: ReadonlyArray<string>;
  ogImagePath?: string;
  social?: boolean;
}

export type HeadPageOptions = {
  pathname: string;
  description?: string;
} & (
  | { title: string; titleByTemplate?: never }
  | { titleByTemplate: string; title?: never }
);
Enter fullscreen mode Exit fullscreen mode

URL construction:

// src/lib/head/url.ts
import { normalizePathname, normalizeUrl } from "@/utils/url";

export function createCanonicalUrl(baseUrl: string, pathname: string): string {
  const normalized = normalizePathname(pathname);

  return normalized === "/" ? baseUrl : `${baseUrl}${normalized}`;
}

export function createAssetUrl(baseUrl: string, path: string): string {
  return `${baseUrl}/${path.replace(/^\/+/, "")}`;
}
Enter fullscreen mode Exit fullscreen mode

Links, with the canonical added only when a page URL is supplied:

// src/lib/head/links.ts
import type { HeadLink } from "./types";

function buildFaviconLinks(): HeadLink[] {
  return [
    {
      rel: "icon",
      type: "image/png",
      href: "/favicon-96x96.png",
      sizes: "96x96",
    },
    { rel: "icon", type: "image/svg+xml", href: "/favicon.svg" },
    { rel: "shortcut icon", href: "/favicon.ico" },
    {
      rel: "apple-touch-icon",
      href: "/apple-touch-icon.png",
      sizes: "180x180",
      type: "image/png",
    },
  ];
}

function buildWebmanifest(): HeadLink[] {
  return [
    {
      rel: "manifest",
      href: "/site.webmanifest",
    },
  ];
}

export function buildHeadLinks(
  stylesheets: ReadonlyArray<string>,
  canonicalUrl?: string
): HeadLink[] {
  return [
    ...stylesheets.map((href) => ({ rel: "stylesheet", href })),
    ...buildFaviconLinks(),
    ...buildWebmanifest(),
    ...(canonicalUrl ? [{ rel: "canonical", href: canonicalUrl }] : []),
  ];
}

export function buildAlternateLinks(url: string): HeadLink[] {
  return [{ rel: "alternate", hrefLang: "x-default", href: url }];
}
Enter fullscreen mode Exit fullscreen mode

Social tags, all keyed consistently so nested-route dedupe works:

// src/lib/head/og.ts
import type { HeadMeta } from "./types";

export interface OgMetaOptions {
  appName: string;
  title: string;
  description: string;
  url: string;
  imageUrl: string;
}

export function buildOgMeta(options: OgMetaOptions): HeadMeta[] {
  const { appName, title, description, url, imageUrl } = options;

  return [
    { property: "og:title", content: title },
    { property: "og:description", content: description },
    { property: "og:site_name", content: appName },
    { property: "og:type", content: "website" },
    { property: "og:url", content: url },
    { property: "og:image", content: imageUrl },
    { property: "og:image:width", content: "1200" },
    { property: "og:image:height", content: "630" },
    { property: "og:image:alt", content: appName },
    { name: "twitter:card", content: "summary_large_image" },
    { name: "twitter:title", content: title },
    { name: "twitter:description", content: description },
    { name: "twitter:image", content: imageUrl },
    { name: "twitter:image:alt", content: appName },
  ];
}
Enter fullscreen mode Exit fullscreen mode

The base meta set and the title resolver:

// src/lib/head/meta.ts
import { buildOgMeta } from "./og";
import type { HeadMeta, HeadPageOptions } from "./types";

export interface HeadMetaContext {
  appName: string;
  themeColor: string;
  robots: string;
  googlebot: string;
  social: boolean;
  ogImage: string;
}

export interface HeadPageMeta {
  title: string;
  description: string;
  url: string;
}

export function resolveTitle(
  titleTemplate: string,
  options: HeadPageOptions
): string {
  return options.titleByTemplate === undefined
    ? options.title
    : titleTemplate.replace("%s", () => options.titleByTemplate);
}

export function buildHeadMeta(
  context: HeadMetaContext,
  page: HeadPageMeta
): HeadMeta[] {
  const { appName, themeColor, robots, googlebot, social, ogImage } = context;
  const { title, description, url } = page;

  const meta: HeadMeta[] = [
    { charSet: "utf-8" },
    { name: "viewport", content: "width=device-width, initial-scale=1" },
    { name: "theme-color", content: themeColor },
    { title },
    { name: "description", content: description },
    { name: "robots", content: robots },
    { name: "googlebot", content: googlebot },
    { name: "format-detection", content: "telephone=no" },
    { name: "mobile-web-app-capable", content: "yes" },
    { name: "apple-mobile-web-app-title", content: appName },
    {
      name: "apple-mobile-web-app-status-bar-style",
      content: "black-translucent",
    },
  ];

  if (social) {
    meta.push(
      ...buildOgMeta({
        appName,
        title,
        description,
        url,
        imageUrl: ogImage,
      })
    );
  }

  return meta;
}
Enter fullscreen mode Exit fullscreen mode

The press itself:

// src/lib/head/buildHead.ts
import { normalizeUrl } from "@/utils/url";

import { buildAlternateLinks, buildHeadLinks } from "./links";
import { buildHeadMeta, resolveTitle } from "./meta";
import type { BuildHeadConfig, HeadPageOptions, HeadResult } from "./types";
import { createAssetUrl, createCanonicalUrl } from "./url";

export type { BuildHeadConfig, HeadPageOptions, HeadResult } from "./types";

const GOOGLEBOT_DEFAULT =
  "index, follow, max-video-preview:-1, max-image-preview:large, max-snippet:-1";

interface HeadContext {
  appName: string;
  baseUrl: string;
  defaultTitle: string;
  titleTemplate: string;
  defaultDescription: string;
  themeColor: string;
  robots: string;
  googlebot: string;
  stylesheets: ReadonlyArray<string>;
  ogImage: string;
  social: boolean;
}

function createHeadContext(config: BuildHeadConfig): HeadContext {
  const {
    appName,
    siteUrl,
    defaultTitle,
    titleTemplate,
    defaultDescription,
    themeColor,
    robots = "index, follow",
    stylesheets = [],
    ogImagePath = "/opengraph-image.jpg",
    social = true,
  } = config;

  if (!titleTemplate.includes("%s")) {
    throw new Error('buildHead: titleTemplate must contain "%s"');
  }

  const baseUrl = normalizeUrl(siteUrl);

  return {
    appName,
    baseUrl,
    defaultTitle,
    titleTemplate,
    defaultDescription,
    themeColor,
    robots,
    googlebot: robots.includes("noindex") ? robots : GOOGLEBOT_DEFAULT,
    stylesheets,
    ogImage: createAssetUrl(baseUrl, ogImagePath),
    social,
  };
}

export function buildHead(config: BuildHeadConfig) {
  const context = createHeadContext(config);

  const globalHead = (): HeadResult => ({
    meta: buildHeadMeta(context, {
      title: context.defaultTitle,
      description: context.defaultDescription,
      url: createCanonicalUrl(context.baseUrl, "/"),
    }),
    links: buildHeadLinks(context.stylesheets),
  });

  const head = (options: HeadPageOptions): HeadResult => {
    const url = createCanonicalUrl(context.baseUrl, options.pathname);

    return {
      meta: buildHeadMeta(context, {
        title: resolveTitle(context.titleTemplate, options),
        description: options.description ?? context.defaultDescription,
        url,
      }),
      links: [
        ...buildHeadLinks(context.stylesheets, url),
        ...buildAlternateLinks(url),
      ],
    };
  };

  return { globalHead, head };
}
Enter fullscreen mode Exit fullscreen mode

Set the plates up once:

// src/lib/head/index.ts
import { siteConfig } from "@/lib/site-config";

import { buildHead } from "./buildHead";

export const { globalHead, head } = buildHead(siteConfig);
Enter fullscreen mode Exit fullscreen mode

Import with import { globalHead, head } from "@/lib/head"; swap @/ for your alias, or use relative paths. The config object is a stand-in for your own constants and environment values.

Install the shared sheet in the root

import { globalHead } from "@/lib/head";
import { HeadContent, Scripts, createRootRoute } from "@tanstack/react-router";

export const Route = createRootRoute({
  head: () => globalHead(),
  shellComponent: RootDocument,
});

function RootDocument({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <head>
        <HeadContent />
      </head>
      <body>
        {children}
        <Scripts />
      </body>
    </html>
  );
}
Enter fullscreen mode Exit fullscreen mode

Defaults print once, and the root emits no page canonical. HeadContent must live in the root <head>.

Stamp a page identity from the match

import { head } from "@/lib/head";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/about")({
  head: ({ match }) =>
    head({ pathname: match.pathname, titleByTemplate: "About" }),
  component: () => <div>About</div>,
});
Enter fullscreen mode Exit fullscreen mode

Canonical, og:url, and alternate link derive from one pathname, so they cannot drift.

Handle dynamic segments

import { head } from "@/lib/head";
import { createFileRoute } from "@tanstack/react-router";

export const Route = createFileRoute("/posts/$postId")({
  head: ({ match }) =>
    head({
      pathname: `/posts/${match.params.postId}`,
      titleByTemplate: "Post",
      description: "A field note",
    }),
  component: () => <div>Post</div>,
});
Enter fullscreen mode Exit fullscreen mode

Route params become a canonical URL without touching the browser.

❌ Do not pass window.location.pathname into head(). It is absent during SSR, and the router already hands you the authoritative path via match.

When to Use It

  • Every page has a stable URL derivable from match.pathname or route params.
  • You want identical defaults: title template, robots, OG image, stylesheets, icons.
  • Your head is pure data, not component state or browser values.
Situation Better tool
Title needs fetched data Route loader plus head reading match.loaderData
Head must follow client-only state A component effect that writes document.title
One route needs a different theme color An extra meta entry in that route's own head
Multiple languages or regions Route-specific hrefLang alternate links
You need head scripts The route scripts option
A single static page with no shared data An inline head object in that route

Smell test: writing window inside head means the URL should come from the match.

How It Works Under the Hood

  1. The plate is fixed at setup. createHeadContext(config) strips trailing slashes from siteUrl, checks the template for %s, and precomputes the OG image URL. A bad template throws at load.

  2. The template handles one placeholder. resolveTitle uses titleTemplate.replace("%s", () => options.titleByTemplate), which replaces only the first %s. The HeadPageOptions union forbids passing both title and titleByTemplate.

  3. Canonicals are normalized, not concatenated. normalizePathname strips leading and trailing slashes and collapses repeats; createCanonicalUrl returns the bare base URL for /. Naive concatenation yields https://atlas.test//about and a trailing-slash variant.

  4. Only the page sheet carries a canonical. globalHead() calls buildHeadLinks(context.stylesheets) with no URL; head() adds one canonical and one alternate. Router dedupe covers nested title and meta, not links. The cost: the root sheet has no canonical, so / needs its own head() entry if it wants one.

  5. The cost is small. Each head() call allocates arrays and objects, and the closure retains config for the app's life. There are no DOM writes or effects. googlebot is derived once: robots containing noindex is reused verbatim, otherwise a verbose default applies.

Phase Work performed Canonical value
Module evaluation buildHead(siteConfig) normalizes and stores context none, no sheet printed
Route match on the server About route calls head() with match.pathname https://atlas.test/about
SSR render HeadContent emits the merged head one canonical link
Discarded render A redirect wins before HTML is sent; the sheet is dropped printed, never shipped
HTML on the wire Browser parses the head one canonical link
Hydration No head recompute, no effect writes to the DOM unchanged
Client navigation to / Leaf sheet unloads; root sheet has no canonical none unless / defines its own

Server rendering note: head functions run on the server and again on client navigation. They must be pure: no window, document, or component state, so the same config and match produce the same head in both places.

Router dedupe does not normalize a bad URL or apply a title template, and head is not a hook, so useLocation() is unavailable; pass match.pathname.

Conclusion

You give up per-page improvisation and get one predictable sheet per URL. The root owns site facts, the leaf owns page facts, and the factory joins them before HTML exists.

  • Keep site-wide values in one config so they cannot drift between routes.
  • Pass match.pathname to every page head; let normalization handle the edges.
  • globalHead() omits canonical links; a home route needing one calls head().

Use this press when many routes share one identity. For one static page, the boring inline head object wins.

Top comments (0)