vi

blog

SEO and link gates on the Next.js build output: check the built HTML, not the source

2 postbuild gates read out/**/*.html: canonical, og:image, two-way hreflang, duplicate titles, sitemap xhtml:link and dead internal links. A failure stops the build before deploy.

Published
Next.js 16SEOhreflangBuild gate
An out/ window in the middle listing a few html and xml files, 3 small cards on the left labeled frontmatter, Seo.jsx and public/ feeding into it, and 2 accent lines running out to 2 checkmarked cards named check:seo and check:links

check:seo and check:links read the HTML in out/ after next build finishes, not the frontmatter. What Google and Facebook receive is HTML, and HTML is the product of frontmatter, components/Seo.jsx, files in public/ and the cover rasterize step. If any link in that chain breaks, the source still looks fine. Both gates sit in postbuild, so an error fails npm run build and the deploy workflow stops there.

postbuild runs the sitemap first and the 2 gates after

json
"postbuild": "node scripts/inline-critical-css.js && node scripts/generate-sitemaps.js && node scripts/check-seo.js && node scripts/check-links.js"

npm runs postbuild right after npm run build, so CI's build:static goes through it too. In the deploy workflow the publish job declares needs: build: a red build ships nothing to Cloudflare.

Both scripts share scripts/lib/out-html.js, which lists every .html file in out/ except _next, 404 and not-found (noindex pages, not public surface). generate-sitemaps.js runs first and fails by itself if the number of blog or project pages in out/ differs from the number of .md files: a post missing from out/ means the build is already broken.

og:image must point to a file that really exists in out/

js
const ogImage = pick(html, /<meta property="og:image" content="([^"]+)"/)
if (!ogImage) errors.push(`${rel}: thiếu og:image`)
else if (ogImage.startsWith(SITE_URL) && !fs.existsSync(path.join(OUT, ogImage.slice(SITE_URL.length)))) {
  errors.push(`${rel}: og:image trỏ file không có trong out/ (${ogImage})`)
}

A post's cover is an SVG, but Facebook, X, LinkedIn and Zalo do not render SVG in og:image. lib/og-image.js turns /covers/x.svg into /covers/x.png for the og tag, and scripts/rasterize-covers.js writes that PNG at prebuild. The frontmatter says .svg and is correct whether the PNG exists or not. Only the HTML tells you which file the og tag points to, and only out/ tells you whether that file is real.

A page with no declared image falls back to localeMeta[locale].ogImage in Seo.jsx. That page's frontmatter does not reveal this, so the gate catches it in the HTML as well.

On each page the gate requires 0 or 3 hreflang tags, x-default pointing to the vi version, and og:locale:alternate whenever the pair is complete. A /page/N page must have no hreflang. It then collects every page into a map keyed by canonical and cross-checks:

js
for (const l of ['vi', 'en']) {
  if (!p.hreflang[l] || l === p.lang) continue
  const other = pages.get(p.hreflang[l])
  if (!other) errors.push(`${p.rel}: hreflang ${l} trỏ tới trang không tồn tại (${p.hreflang[l]})`)
  else if (other.hreflang[p.lang] !== canonical) errors.push(`${p.rel}: hreflang ${l} không trỏ ngược lại`)
}

pages.get looks up a real page in out/ instead of just comparing strings, so an hreflang pointing at a URL that does not exist also goes red. The vi/en pair is joined by translationOf, as covered in the post on the bilingual blog.

Duplicate titles are an error only the HTML reveals. The blog list is 1 source file but produces many /blog/page/N pages, and without a suffix they share a title. Seo.jsx appends (Trang N) or (Page N) to the title and description of those pages, and the gate reports duplicates in one line:

js
for (const [title, rels] of byTitle) if (rels.length > 1) errors.push(`title trùng "${title}": ${rels.join(', ')}`)

The sitemap gets its own check. For each <url> in out/sitemap-*.xml, the xhtml:link tags must equal the hreflang in that page's own HTML:

js
if (JSON.stringify(linkMap(body, 'xhtml:link')) !== JSON.stringify(page.hreflang)) {
  errors.push(`${name}: ${loc} có xhtml:link lệch hreflang trong HTML`)
}

The 2 sides go through 2 different code paths. generate-sitemaps.js reads translationOf from frontmatter and keeps only pairs where both pages exist in out/; the HTML gets its pair from getAlternates in lib/translations.js. One fact, built 2 ways, and the gate compares them. JSON.stringify is sensitive to key order, so both sides must print vi, en, x-default in the same order.

check-links.js takes every <a href="/..."> on every page, skips /_next and //, then looks for the matching file in out/:

js
function exists(href) {
  const clean = decode(href.split('#')[0].split('?')[0]).replace(/\/$/, '') || '/'
  if (clean === '/') return fs.existsSync(path.join(OUT, 'index.html'))
  const p = path.join(OUT, clean)
  return (
    fs.existsSync(p + '.html') ||
    fs.existsSync(path.join(p, 'index.html')) ||
    (path.extname(clean) && fs.existsSync(p))
  )
}

/x matches out/x.html or out/x/index.html, the same way Cloudflare's auto-trailing-slash serves the site. The function only looks for files in out/ and does not read _redirects, so a link to an old /blog/<slug> URL counts as dead even though the 301 still works. That is useful: links in posts have to point straight at the new URL.

The second rule applies only inside <article> (post body, table of contents, related-post cards): a vi page may not link to /en/... and the reverse, except to the home page /. LanguageSwitch and the footer sit outside <article>, so they may cross languages. Orphan posts (no other post links to them) only print a warning and do not fail.

Why check the output and not the source

The SEO plan for the bilingual site required running the gate against the old out/ before fixing anything, and it had to be red. The figure measured at review was 270 errors across 70 pages, including 20 pages without og:image and 4 vi list pages plus 4 en list pages sharing titles. Many of those errors have no frontmatter line to point at: pages with no declared image, and 4 /page/N pages generated from 1 file. A gate that has never gone red has not proven it catches anything.

There are 3 reasons to check the output:

  • 1 source file can produce many pages (pagination), and the error sits on each page.
  • Code sits between frontmatter and HTML: the og:image fallback, the (Trang N) suffix, the .svg to .png swap, the conditions for printing hreflang.
  • Many things only exist after the build: the sibling PNGs, sitemap-*.xml, the exported pages.

What these 2 gates do not check

  • The content of the og image. The gate checks that the file is in out/, so editing an SVG and forgetting to rasterize still passes with the old PNG. A human eye is the last net.
  • External links. check-links.js only looks at href values starting with /; outbound links are checked by the weekly cron check-content-freshness.yml.
  • Anchors. The gate cuts the #... part before looking up the file, so /x#khong-co still passes.
  • Length. A description outside 70-165 characters or a title over 65 characters is only a warning and does not turn the build red.

Related posts

all posts →