Skip to content

An SEO Implementation Contract for a Next.js Build: Page Records In, Metadata, Schema and Sitemap Out

Treat SEO output as a contract between your content data and the HTML. Define one page record, state exactly what each field must produce, and test that on a production build. This article includes a tested synthetic Next.js example and the traps it catches.

A paper page record branches to Head, JSON-LD, Sitemap and Robots output sheets.
One page record feeds canonical, Open Graph, JSON-LD, sitemap and robots outputs, with assertions for URLs, site name, image delivery, stable IDs and indexability.
Contract choices for a synthetic app; image delivery is separate. Truthful dates and content remain editorial checks.

Text equivalent. Implementation contracts Teaching diagram • Define the output. Test the delivery. Page record path · title · description dates · image · indexable Canonical URL equals the record Open Graph Keep siteName; check file delivery JSON-LD @graph Stable IDs; visible content Sitemap row Indexable only; truthful lastmod Robots meta Noindex remains crawlable Synthetic contract choices • metadata existence is not proof that the share-image URL delivers a file

Full-size diagram

Most technical SEO problems in a product build aren't knowledge problems. The team knew pages need canonicals. What failed was the plumbing. A layout's metadata got silently replaced, a sitemap stamped every page with today's date, or a "hide from search" flag turned into a robots.txt rule that stopped Google from ever seeing the noindex.

The fix is to specify SEO as a contract. Each page is described once, as a record. The contract says exactly what that record must produce in the HTML head, the structured data, the sitemap and the robots rules. A test checks every output on a production build. If you're scoping a Next.js product, put this in the statement of work. "SEO-ready" is not a specification.

Scope. This covers the mechanics of metadata output. It isn't a checklist of SEO fundamentals; for those, see website SEO basics that drive results. Language alternates (hreflang) and retiring old URLs are separate jobs, so they're left out here. The code and test results below come from a synthetic example app (example.com, Next.js 16.4.5, run on localhost). Where I mention this site's own implementation, that's an observation from its source at a pinned commit, to be reconciled with the current code before publication. None of it is a promise about how any client build was configured.

1. The page record

Everything starts from one typed record per indexable or crawlable page:

FieldMeaningRule
pathCanonical pathNo query string, no trailing-slash ambiguity. One form only
titlePage titleUnique; also used as the headline on articles
descriptionMeta descriptionWritten for the page; not auto-truncated body text
typearticle or pageDecides which structured data node is emitted
publishedFirst publication dateArticles only
modifiedDate of the last significant editOmit it if you can't defend one
imageShare image pathOptional. If absent, emit no image rather than a generic one that misdescribes the page
indexableIs this page intended to be eligible for search?false means noindex. It does not mean "block crawling" (see §4). true signals intent; it can't make a page appear

The record lives next to the content: a CMS entry, a TypeScript array, or front matter. Every output is derived from it, so there's nothing to keep in sync by hand.

2. The contract: record field → expected output → test

This is the artifact to hand to whoever builds the site. The rules in it are this contract's choices, not Google requirements: the brand suffix, an explicit index, follow, leaving out priority/changefreq, and the image and date policies are all decisions you could make differently. The right-hand column says what the synthetic test actually checks.

Record inputExpected outputHow to test it
path<link rel="canonical"> = absolute self URL; og:url identicalTested: both compared to origin + path
title<title> = title | Brand; og:title; WebPage name; Article headline; an <h1> in the bodyTested: exact matches; the <h1> is searched in <body> with scripts removed
description<meta name="description">; og:description; WebPage descriptionTested: exact matches
typeog:type article or website; one Article node with headline, datePublished, dateModified when known, image when present, only on articlesTested
published / modifiedarticle:published_time / article:modified_time; schema dates; sitemap <lastmod> = modifiedTested: outputs equal the record, and lastmod is absent for the undated page. The test can't prove the record's date reflects a significant edit. That's an editorial control
imageog:image (absolute, declared 1200×630); schema imageTested: URL and declared dimensions, absent when the record has none. File delivery is a separate check (below)
indexable = truerobots meta index, follow; a sitemap rowTested
indexable = falserobots meta noindex; no sitemap row; not disallowed in robots.txtTested: meta value, row absent, and no User-agent: * Disallow prefix covers the path (a minimal check, see §4)
(site level)robots.txt with host-wide rules and a Sitemap: pointer; sitemap with no priority or changefreqTested
(unknown path)HTTP 404Tested for one unknown path

In the synthetic app (Node 24.22.1, Next.js 16.4.5, next build + next start on localhost), the test recorded 59 PASS / 0 FAIL across three records: an article with dates and an image, a page with no defensible modified date, and a non-indexable utility page. To show the test can fail, three deliberately broken variants were built and run:

VariantResult
siteName removed from the page builder56 PASS / 3 FAIL (og:site_name missing on all three pages)
Disallow: /tools/ added to robots.txt58 PASS / 1 FAIL (the noindex page is now blocked)
<h1> replaced, so the title only appears in the head and JSON-LD56 PASS / 3 FAIL

A separate image-delivery check requested the article's share image from the local server and got HTTP 404, because the synthetic app ships no image file. The metadata test passed regardless. That's exactly why file delivery needs its own check.

3. Metadata: one builder, and the shallow-merge trap

In the App Router, each route returns metadata from generateMetadata. Write one function that turns a record into a Metadata object, and call it everywhere. This is a partial, simplified extract of the tested builder. It needs the PageRecord type, the SITE and SITE_NAME constants and Next's Metadata type, and it isn't a complete app:

ts
export function buildMetadata(r: PageRecord): Metadata {
  const url = new URL(r.path, SITE).toString()
  return {
    title: { absolute: `${r.title} | ${SITE_NAME}` },
    description: r.description,
    alternates: { canonical: url },
    robots: r.indexable ? { index: true, follow: true } : { index: false, follow: true },
    openGraph: {
      siteName: SITE_NAME,             // must be repeated here (see below)
      url, title: r.title, description: r.description,
      type: r.type === 'article' ? 'article' : 'website',
      ...(r.image ? { images: [{ url: new URL(r.image, SITE).toString(), width: 1200, height: 630 }] } : {}),
      ...(r.type === 'article'
        ? { publishedTime: r.published, ...(r.modified ? { modifiedTime: r.modified } : {}) }
        : {}),
    },
  }
}

Google recommends absolute URLs for canonicals: "Use absolute paths rather than relative paths with the rel="canonical" link element." Next.js's metadataBase can compose relative values into absolute ones. Building the full URL in one place makes the output easy to assert either way.

The trap. The Next.js docs say metadata from nested segments is "shallowly merged". Nested fields "such as openGraph and robots that are defined in an earlier segment are overwritten by the last segment to define them." In the synthetic app the root layout sets openGraph.siteName. When the page builder's openGraph object left siteName out, og:site_name disappeared from all three pages. The layout value was not merged in, and the test failed three times. Put it back in the builder and the test passes. In this site's source (pinned commit), the same mechanism is why the RSS autodiscovery link is merged inside the metadata helper: a page's alternates would otherwise replace the layout's. A contract test is what catches this class of bug. Reading the code usually doesn't.

4. Robots: per-page directives are not host rules

There are two separate controls here, and indexable should only ever drive one of them.

  • Per-page: <meta name="robots" content="noindex">, or the X-Robots-Tag header for non-HTML files. This keeps a crawlable page out of results.
  • Host-level: robots.txt. This controls what crawlers fetch.

Google is explicit about how they interact: "For the noindex rule to be effective, the page or resource must not be blocked by a robots.txt file… If the page is blocked by a robots.txt file or the crawler can't access the page, the crawler will never see the noindex rule, and the page can still appear in search results." So indexable: false must produce noindex and remove the sitemap row, and it must not add a Disallow. In the synthetic app, robots.txt is written separately with host-wide rules only (Disallow: /api/). The test checks that no Disallow prefix in the User-agent: * group covers a record's path, and the /tools/ variant above shows it failing. That's a deliberately minimal reader, not a robots.txt parser: it ignores wildcards, $ anchors, Allow precedence and agent-specific groups. Use a real parser if your rules use any of those.

Neither control is access control. A page that must not be seen needs authentication.

5. Structured data: one graph with stable IDs (a design choice)

The synthetic app emits one JSON-LD @graph per page. It holds Organization (/#org), WebSite (/#website), WebPage ({url}#webpage), and an Article node on articles that points at the WebPage and the publisher by @id. This site's source (pinned commit) does the same: one @graph per page, with stable @ids for shared entities.

That's a design choice, not a requirement. Separate JSON-LD blocks are valid too. The graph's advantages are that each entity is defined once and referenced everywhere, and that tests can find nodes by @id. The cost is a bigger payload on every page, plus one central builder that everyone has to understand.

The rules that are Google's:

  • "Don't mark up content that is not visible to readers of the page." The test checks one field of this, that the schema headline is rendered as an <h1> in the body. Other properties need their own checks or an editorial review.
  • Structured data can make a page eligible for a feature, but "Google does not guarantee that your structured data will show up in search results, even if your page is marked up correctly."

Two implementation details from the Next.js JSON-LD guide matter. Render the graph in a <script type="application/ld+json">. And because JSON.stringify "does not sanitize malicious strings used in XSS injection", escape < whenever any field could contain user or CMS text. The guide's replacement, as used in the synthetic app:

ts
const jsonLd = JSON.stringify(value).replace(/</g, '\\u003c')

Escaping protects the script element. It doesn't validate the graph's facts.

6. Sitemap: truthful lastmod, or none

The Next.js sitemap docs show lastModified: new Date() on every URL. That's an illustration of the API, not a truthfulness recommendation. Google's guidance is the constraint:

  • "Google ignores <priority> and <changefreq> values."
  • "Google uses the <lastmod> value if it's consistently and verifiably (for example by comparing to the last modification of the page) accurate," and it "should reflect the date and time of the last significant update to the page."

A build-time date on every page can make lastmod unreliable. Use actual significant-update dates. The contract rule is therefore: lastmod = record.modified; no date, no tag. In this site's source (pinned commit), case-study pages have no lastmod because, as the source comment puts it, a build-time date "would be a fake signal". The synthetic sitemap emits <lastmod>2026-10-12</lastmod> for the article and nothing for the undated page. Only indexable records get a row.

One operational detail: Next.js documents sitemap.js as "a special Route Handler that is cached by default". A static sitemap is fine as long as you rebuild when records change. Don't expect it to refresh by itself.

7. Running the contract test

Run it against next build && next start on your machine or in CI, never against next dev, because development output differs. The synthetic test does four things:

  1. Fetches each record's URL and checks the status, canonical, title, description, Open Graph fields, robots meta, JSON-LD nodes and the body <h1> against the record.
  2. Fetches /sitemap.xml and /robots.txt and checks row presence, lastmod, the Sitemap: pointer and the minimal Disallow check.
  3. Requests one unknown path and expects 404.
  4. Exits nonzero on any mismatch, so a configured release gate can stop publication. It doesn't fail a build that has already finished unless you wire it into one.

Limits of the test: it proves your HTML says what the contract says. It doesn't prove what a search engine will index or show. The live host can also differ from the local build (redirects, headers added by the platform, environment variables such as the site URL). Check those once at launch. Then rely on Search Console's indexing reports, not on guesses.

Edge cases to add to your own matrix: image files that are missing (the separate delivery check above caught one), two records with the same path, a title containing < or quotes, and pagination or filtered URLs. Decide whether those last ones get their own records or canonicalize to the base list.

Language alternates for an English and Persian tree are covered in building a bilingual English–Persian Next.js site. Retiring old URLs without leaving them in the index is covered in retiring old portfolio pages.

What this costs, and when it's worth it

A record type, a builder, a graph function and one test file is a small amount of code. The real cost is discipline: every new page type has to come through the record, or the contract doesn't cover it. It pays off as soon as more than one person adds pages, or a content system feeds the site. Those are exactly the cases where metadata drifts quietly. The contract covers crawlable metadata, structured data and the sitemap; it isn't a separate AI Overviews technical package, and what Google's docs say about AI search answers that question.


Scoping a Next.js product and want SEO specified, not promised? I can write the page-record contract and its test for your build as part of Technical Growth Infrastructure. Start here.


Sources

Put the thinking to work

What could this change for you?

Tell me what you’re building — I’ll tell you honestly where I’d start.

Start a project with me