Sub topic 15
Generating tags in templates and frameworks
This chapter assumes you can write a title, a meta description, and a canonical link by hand. It also assumes you know what a query string is and have used some server-side template or JavaScript framework. Here you will generate those tags from code, so every page gets correct values without anyone typing them.
Why generate instead of hand-write
Hand-written tags work for ten pages. At a thousand pages, they drift. Someone forgets a description, copies a title between pages, or pastes a staging URL into a canonical. A template fixes this by making the head a function of page data. The page supplies a title, a description, and a path. The template supplies everything else.
Generation also creates its own failure modes. A bug in one template ships the same wrong tag to every page that uses it. Treat the head template as high-risk code and test it.
The shape of a good head template
A good template does four things:
- It takes explicit inputs: page title, description, and path.
- It builds derived values, such as the site-suffixed title and the canonical URL, in one place.
- It escapes every value before putting it in HTML.
- It fails loudly, or uses a safe fallback, when an input is missing.
A runnable example in Node.js
This example has no dependencies. It builds the canonical URL from a fixed site origin, not from the request's Host header. A canonical built from request data can be poisoned by a forged header, and it would also change between your staging and production hosts.
const SITE_ORIGIN = "https://www.example.com";
const SITE_NAME = "Example Store";
function escapeHtml(value) {
return String(value)
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Keep only query parameters that change the page content.
function canonicalUrl(requestPath, allowedParams = []) {
const parsed = new URL(requestPath, SITE_ORIGIN);
const url = new URL(SITE_ORIGIN);
url.pathname = parsed.pathname;
const kept = new URLSearchParams();
for (const key of allowedParams) {
const value = parsed.searchParams.get(key);
if (value !== null) kept.set(key, value);
}
url.search = kept.toString();
url.hash = "";
return url.toString();
}
function renderHead({ title, description, path, allowedParams }) {
if (!title) throw new Error("Every page needs a title");
const fullTitle = `${title} | ${SITE_NAME}`;
const lines = [
'<meta charset="utf-8">',
`<title>${escapeHtml(fullTitle)}</title>`,
];
if (description) {
lines.push(`<meta name="description" content="${escapeHtml(description)}">`);
}
lines.push(
`<link rel="canonical" href="${escapeHtml(canonicalUrl(path, allowedParams))}">`
);
return lines.join("\n");
}
console.log(
renderHead({
title: "Trail Running Shoes",
description: "Compare cushioned trail shoes & read fit tips.",
path: "/shoes/trail-running?color=red&utm_source=newsletter#reviews",
allowedParams: ["color"],
})
);Running it prints:
<meta charset="utf-8">
<title>Trail Running Shoes | Example Store</title>
<meta name="description" content="Compare cushioned trail shoes & read fit tips.">
<link rel="canonical" href="https://www.example.com/shoes/trail-running?color=red">Several design choices matter here:
- Allowlist, not blocklist. A blocklist of tracking parameters misses the next one a marketing team invents. An allowlist of parameters that change content cannot go stale in that way.
- Fixed origin. The protocol and host are never read from the request, so the canonical is always absolute, HTTPS, and on your preferred host.
- Escaping. Without it, a title containing a quote or
<can break the page or inject markup. - Optional description. A missing description is omitted, not rendered as
content="". The search engine then builds a snippet from the page text, as described in the snippet chapter.
Frameworks: where the logic lives
Most frameworks give you a place to define metadata per page and a layout that merges it. The mechanism differs, but the pattern is the same.
| Framework | Typical mechanism |
|---|---|
| Next.js (App Router) | `metadata` export or `generateMetadata()` function |
| Nuxt | `useSeoMeta()` and `useHead()` composables |
| Astro | Props passed to a layout that renders the head |
| Django or Jinja2 | `{% block title %}` overridden in child templates |
| Rails | `content_for :title` read by the layout |
| Static site generators | Front matter fields read by the layout |
A Next.js page that builds its metadata from data looks like this:
// app/shoes/[slug]/page.js
import { getShoe } from "@/lib/shoes";
export async function generateMetadata({ params }) {
const shoe = await getShoe(params.slug);
return {
title: shoe.name,
description: shoe.summary,
alternates: {
canonical: `https://www.example.com/shoes/${shoe.slug}`,
},
};
}Next.js can also take a metadataBase in the root layout, so relative canonical paths resolve to an absolute URL. Check your framework's documentation to see whether it does this, and to see what it emits when you pass a relative value. The tag you want in the output is always absolute.
Rendering location matters
Search engines can run JavaScript, but they do it in a separate, delayed rendering step. If your canonical or title only appears after client-side code runs, the crawler may index the raw HTML first and see different values. Worse, the raw HTML and the rendered DOM can disagree, which sends conflicting signals.
Prefer server-side rendering or static generation for head tags. If a single-page app must set them in the browser, confirm what the raw HTML contains by fetching it without running scripts.
Common template bugs
- Wrong canonical on paginated or filtered pages. Copying the page-one URL into every page of a series tells search engines that pages two to ten are duplicates of page one. Generate a canonical that includes the
pageparameter. - Environment leaks. A staging host in the canonical, or a
noindexthat was meant for staging, reaches production. Take the origin from a per-environment setting and test it in your deploy checks. - Fallback text on every page. A default description like "Welcome to our site" on pages without data creates thousands of duplicates. Omit the tag, or fail the build.
- Unescaped values. Product names with ampersands or quotes are the usual trigger.
- Trailing slash and case drift. If the router serves
/Shoes/and/shoes, the canonical function must pick one form and apply it everywhere, backed by a redirect.
Test the output, not the template
Unit tests on the head function are cheap and catch most regressions. Check for exactly one title, at most one description, exactly one canonical, an absolute HTTPS canonical, and no tracking parameters. A build-time check can then crawl generated output for duplicate titles. The next chapter covers auditing in more detail.
Exercise
A product listing is served at /shoes?page=2&sort=price&utm_campaign=spring. Using the canonicalUrl function from this chapter, which allowedParams value gives a canonical that keeps the page number but drops sorting and tracking? What canonical results?
Show answer
Pass allowedParams = ["page"]. The result is https://www.example.com/shoes?page=2. The sort and utm_campaign parameters are not on the allowlist, so they are dropped. Keeping page means page two is not declared a duplicate of page one.
Exercise
A single-page app sets document.title and the canonical link in JavaScript after load. The raw HTML has a generic title and no canonical. Name one risk and one fix.
Show answer
Risk: the crawler may index the raw HTML first, so it sees the generic title and no canonical until the delayed rendering step runs, and the two versions can conflict. Fix: render the head on the server, or generate static HTML at build time, so the tags are in the first response.