Skip to content

Private previewMost of the architecture is written. First public release in 2027.

Head

useHead sets the <title>, meta tags, links, scripts, styles and the attributes of <html> and <body>. Hamur renders them into the server HTML and keeps them in step after every navigation.

tsx
import { useHead } from "@hamur/adapter-react";

export default function Contact() {
  useHead({
    title: "Contact",
    htmlAttrs: { lang: "en" },
    meta: [{ name: "robots", content: "noindex" }],
    link: [{ rel: "canonical", href: "https://example.com/contact" }],
  });
  return <h1>Contact</h1>;
}

Entries stack in layers, lowest first: the site defaults (see SEO), app.head from the config, the metadata files, entries an app plugin pushes, the head of each matched route (its page meta.head and its load file's head, outermost route first) and last the components (useHead, useSeoMeta), the root component before the layout before the page. For the same key the later one wins, so where an entry sits does not depend on when it was pushed. A tag is keyed by name, property or http-equiv for meta, by rel="canonical" or rel and href for links, and by id or src for scripts. Set key on any tag to choose its key. A tag without a key is never merged. htmlAttrs and bodyAttrs merge per attribute.

useHead removes its entries when the component unmounts. In the browser an entry exists from the component's commit to its unmount: a render React throws away while a useFetch suspends, a component that throws after useHead inside an ErrorBoundary, and a page you leave at once all leave no tags behind.

Attributes of <html> and <body>

Attributes you set with htmlAttrs and bodyAttrs go with the entry that set them. A page that sets htmlAttrs: { lang: "tr" } and is loaded from the server gives up lang when you navigate to a page that does not set it. The server marks the names it wrote in a data-hamur-head-attrs attribute on <html> and <body>; the browser reads it once, takes those attributes as its own and removes the marker. An attribute the marker does not list, such as one in your own index.html, is put back to its value instead of removed.

Repeated tags

A meta tag may repeat within one entry when its key is one that Open Graph and the search engines let repeat: a property or name that starts with og:, article:, book:, profile: or author:, theme-color, google-site-verification, twitter:image and twitter:image:*. Every tag is kept, in order.

ts
useHead({
  meta: [
    { property: "og:image", content: "/a.png" },
    { property: "og:image", content: "/b.png" },
  ],
});

A structured property (og:image:*, og:video:*, og:audio:* and twitter:image:alt) belongs to the root tag before it (og:image, og:video, og:audio, twitter:image): within one entry the tags keep their written order (an image, its width, the next image, its width), and another entry that sets the root replaces the whole group, width and alt included. A structured property in an entry that has no tag of its root is dropped; hamur dev logs [hamur] og:image:alt without og:image in the same head entry is ignored once per key.

Another entry that sets og:image replaces the whole group. A tag with its own key is never part of the group; it replaces only the tag with that key. Other meta, such as description, keeps one tag per key: the last in the entry wins.

Search and social tags

useSeoMeta takes flat keys and writes the meta tags: description, robots, author, keywords, themeColor, colorScheme, og* (such as ogTitle and ogImage), twitter* (such as twitterCard), the site verification keys, the appleMobileWebApp* keys and the app link keys (alIosUrl, alAndroidPackage and the like), next to title and titleTemplate.

tsx
import { useSeoMeta } from "@hamur/adapter-react";

export default function Product() {
  useSeoMeta({
    title: "Anvil",
    description: "A very heavy anvil.",
    ogImage: "https://example.com/anvil.png",
    twitterCard: "summary_large_image",
  });
  return <h1>Anvil</h1>;
}

Safe input

useHeadSafe is useHead for input that comes from outside the app, such as a CMS field or a user's profile. It keeps an allow-list and drops the rest.

tsx
import { useHeadSafe } from "@hamur/adapter-react";

export default function Profile({ bio, website }: { bio: string; website: string }) {
  useHeadSafe({
    title: bio,
    meta: [{ name: "description", content: bio }],
    link: [{ rel: "me", href: website }],
  });
  return <h1>{bio}</h1>;
}

It keeps title and titleTemplate as strings; htmlAttrs class, lang and dir; bodyAttrs class; meta name, property, content and media; links whose rel tokens are all alternate, author, help, icon, apple-touch-icon, license, me, next, prev or search and whose href is relative or http: or https:; JSON and JSON-LD scripts; jsonLd; and tagPosition and tagPriority. It drops style, noscript, base, http-equiv, charset, key, a script id, every on* attribute, src, templateParams and anything else. In hamur dev each drop logs one line without the value, such as [hamur] useHeadSafe dropped link[0].href: the scheme "javascript:" is not http: or https:. The type is HeadSafeInput.

Server-only tags

useServerHead and useServerSeoMeta write tags for the server render only. The tags stay in the document after hydration and every navigation, the browser never runs the call, and the client build removes its arguments from the chunks. Use them for what only a crawler or a link preview reads, such as site verification.

tsx
import { useServerSeoMeta } from "@hamur/adapter-react";

export default function Home() {
  useServerSeoMeta({ googleSiteVerification: "abc123", ogType: "website" });
  return <h1>Home</h1>;
}

They take no title or titleTemplate, since the browser would change the title at hydration. A tag the browser sets for the same slot, such as the same meta name or the canonical link, replaces the server one.

Position and priority

Tags take two options that are never written as attributes. tagPosition is "head" (default), "bodyOpen" or "bodyClose": a bodyOpen tag is written first in <body> and a bodyClose tag last. It applies to link, script, style and noscript. tagPriority is "critical", "high" or "low" and applies to every tag. noscript and base are head input too, and innerHTML is the one name for the body of a script, style or noscript; there is no textContent.

Hamur orders <head> itself: charset, viewport, base, the CSP and nonce meta tags and the import map come first, then the title, then the tags sorted by priority (critical, high, unset, low) and, within one, by a fixed weight (http-equiv meta, title, preconnect, async scripts, @import styles, classic scripts, stylesheets and styles, preload and modulepreload, defer and module scripts, prefetch, the rest), then in the order written. The tags of app.head take the nonce and, with hash CSP, their hash, so a tag manager is an app.head.script with tagPosition: "head" and its noscript twin with tagPosition: "bodyOpen". Markup that is not a head tag is a server plugin's render:html hook; app.rawHtml and app.scriptsAt do not exist.

Template params

templateParams fill %name and %name.sub in title, a string titleTemplate and every meta content. They merge across entries per key. %separator defaults to |, collapses when repeated and is removed at either end of the title. %site.name, %site.url and %site.description default to the site config. A param that is unset stays as written, and %s stays the title.

tsx
import { useHead } from "@hamur/adapter-react";

export default function Post() {
  useHead({
    title: "Anvil",
    templateParams: { separator: "·", site: { name: "Forge" } },
    titleTemplate: "%s %separator %site.name",
    link: [{ rel: "preload", href: "/hero.avif", as: "image", tagPriority: "high" }],
    script: [{ src: "/chat.js", async: "", tagPosition: "bodyClose", tagPriority: "low" }],
    noscript: [{ innerHTML: '<img src="/pixel.gif" alt="">', tagPosition: "bodyOpen" }],
    jsonLd: { "@type": "Product", name: "Anvil" },
  });
  return <h1>Anvil</h1>;
}

Structured data

jsonLd takes one object or a list. Each becomes a <script type="application/ld+json"> in the head, with "@context": "https://schema.org" added when it has none, its text escaped so no value can close the element, and the request's CSP nonce. Objects with one @id keep one tag: the later entry's, at the first one's place. An object without @id is never merged. A value JSON.stringify refuses (a cycle, a BigInt) throws its TypeError when the head renders.

Head from the route

A load file may export head beside load. It receives the load context and the data load returned, and answers a head input; seo in it becomes meta in the same entry.

ts
import type { Load, LoadHead } from "hamur/app";

interface Post {
  title: string;
  summary: string;
  slug: string;
}

async function getPost(slug: string): Promise<Post> {
  return { title: "Hello", summary: "First post", slug };
}

export const load = (async ({ params }) => ({ post: await getPost(params.slug as string) })) satisfies Load;

export const head = (({ data }) => ({
  title: data.post.title,
  seo: { description: data.post.summary, ogType: "article" },
  jsonLd: { "@type": "BlogPosting", "@id": `https://example.com/blog/${data.post.slug}#article`, headline: data.post.title },
})) satisfies LoadHead<typeof load>;

It runs on the server after the route's loads, in the browser at hydration and after each navigation, with no request of its own, and on static output with the data of the payload file. Its entry is in the route layer, so a component's useHead still wins for the same key. A throwing head is a load error of its route. Write it in the load file: a page or layout file that exports head fails the build with app/pages/x.tsx exports head, which never runs and reaches the browser: head goes in app/pages/x.load.ts.

A page's meta.head is a head input that needs no data. It is read with the route, so a page with meta.ssr: false still gets it in its shell.

ts
import type { PageMeta } from "hamur/app";

export const meta = {
  head: {
    htmlAttrs: { lang: "tr" },
    titleTemplate: (title) => (title ? `${title} | Mağaza` : "Mağaza"),
  },
} satisfies PageMeta;

Head components

HeadTitle, HeadMeta, HeadLink, HeadScript, HeadStyle, HtmlAttrs and BodyAttrs are the same input as components, for a tag inside a conditional branch of the markup. Each takes props only, pushes one entry for as long as it is mounted, server render included, and renders nothing. HeadTitle takes title and template. They exist in every adapter but html; the Head prefix keeps them apart from Link and from your own Title.

tsx
import { BodyAttrs, HeadMeta, HeadTitle, HtmlAttrs } from "@hamur/adapter-react";

export default function Article({ summary, dark }: { summary?: string; dark: boolean }) {
  return (
    <article>
      <HeadTitle title="About" />
      <HtmlAttrs lang="en" />
      {summary && <HeadMeta name="description" content={summary} />}
      {dark && <BodyAttrs class="dark" />}
      <h1>About</h1>
    </article>
  );
}

Icons

An icon file in app/ needs no code. favicon.ico, icon.(ico|png|svg|jpg|jpeg), icon<n>.* (n digits) and apple-icon.(png|jpg|jpeg), apple-icon<n>.* become links on every document: <link rel="icon" href type sizes> and <link rel="apple-touch-icon" href sizes>, in that order (favicon.ico, icon, icon<n>, apple-icon, apple-icon<n>), after the links of app.head.

favicon.ico is served unhashed at <app.baseURL>favicon.ico; the others get icon-<hash>.<ext> under app.buildAssetsDir. sizes is read from the file's header at build time ("32x32", every entry of an ICO as "16x16 32x32", "any" for an SVG). A file that is not what its extension says fails the build, for example app/icon.png: not a PNG file (no IHDR chunk). public/favicon.ico together with app/favicon.ico fails it with public/favicon.ico and app/favicon.ico both exist; keep one. Icons of the app's own app/ are read; a layer's are not.

Open Graph and Twitter images

opengraph-image.(png|jpg|jpeg|gif) and twitter-image.(png|jpg|jpeg|gif) in app/ or in a folder of app/pages/ need no code. The file applies to every page in its folder and below, and to the page <folder>.<ext> beside the folder (blog.tsx for blog/opengraph-image.png); the nearest file wins, and app/ is the last resort. Group folders such as (marketing)/ count as folders.

  • opengraph-image gives og:image, og:image:type, og:image:width and og:image:height (read from the file's header at build time), and og:image:alt when opengraph-image.alt.txt sits beside it (UTF-8, trimmed).
  • twitter-image gives twitter:image, and twitter:image:alt from twitter-image.alt.txt.
  • The file is emitted as <name>-<hash>.<ext> under app.buildAssetsDir. The URL is absolute through site.url; without it the build warns og:image needs site.url for an absolute URL; the path is written once and writes the path.
  • A page's own useSeoMeta({ ogImage }) or useHead entry that sets og:image replaces the whole group, so the file's width and alt never describe another image.
  • A file over 8 MB (opengraph-image) or 5 MB (twitter-image) is a build warning naming the file; it is still emitted. A file that is not what its extension says fails the build with its path.
  • A page file named opengraph-image or twitter-image fails the build: app/pages/blog/opengraph-image.tsx: "opengraph-image" is the name of a metadata file; an Open Graph image is a .png, .jpg, .jpeg or .gif file, and a generated one comes from @hamur/og-image or a handler route. A generated image is a handler route whose URL the page sets with useSeoMeta({ ogImage }).
  • Only the app's own app/ and app/pages/ are read; a layer's files are not, and an error page has none.

Defaults

Every page starts with <meta charset="utf-8"> and a viewport meta. Meta you add to app.head.meta in the config is layered over them, so the charset and viewport stay unless you set a tag with the same key; a viewport of your own replaces the default one.

Title template

app.head.titleTemplate in the config wraps every title; %s is the title.

ts
import { defineConfig } from "hamur";

export default defineConfig({
  framework: "react",
  app: {
    head: {
      titleTemplate: "%s · My app",
      meta: [{ name: "description", content: "My app" }],
    },
  },
});

Set in the config, the template applies to the title of a layout or a page too. The page's own useHead comes last, so its title wins over the layout's, and a template it sets wins over the config's. titleTemplate may also be a function in useHead. The last title and the last template set win, and the template applies to the final title. A string template with no title renders nothing; a function is called with undefined in that case, so it can return a default.

tsx
import { useHead } from "@hamur/adapter-react";

export default function Landing() {
  useHead({ titleTemplate: (title) => (title ? `${title} | Shop` : "Shop") });
  return <h1>Welcome</h1>;
}

Layouts do not wrap the error page, so a template set only by a layout does not apply to it; set the template in app.head.