When a site moves from WordPress to Next.js or Astro, the content usually survives the move. The quiet loss is everything the old CMS did for free: the related posts plugin, the category archives, the tag pages, the little “you might also like” block at the bottom of every article. WordPress VIP’s guide to headless SEO makes the same point: going headless means rebuilding those pieces yourself.
I think that’s an opportunity as much as a chore. On a static or headless site, the build step already has every page in memory. It’s the cheapest, most predictable place to decide which pages link to which, and to write those links into the HTML before anyone, human or crawler, asks for the page.
This post shows how I do it on Next.js and Astro: a small scoring function that picks related pages from tags, categories and (optionally) embeddings, a “where this is mentioned” list, and pinned links from a reviewed list of approved links. All of it runs at build time, and all of it ends up as plain <a href> links. The code is free, with two working example sites.
Free code
Build-time internal linking for Next.js and Astro: a dependency-free scoring library, a mentions index, approved-link pinning and two example sites that build the same links.
On this page
- Why build time is the right moment for Next.js SEO
- Three kinds of links you can build automatically
- How the related-pages score works
- What it produces on a real build
- Next.js: the App Router walkthrough
- Astro: content collections walkthrough
- Using a headless CMS instead of Markdown
- Limits and pitfalls
- Check the links you ship
- What the course adds
- Frequently asked questions
Why build time is the right moment for Next.js SEO
Most Next.js SEO advice covers metadata, sitemaps and rendering. Internal links get less attention, even though they are how search engines discover pages and understand how they relate, a theme I covered in blog and site architecture for the AI search era. Google’s documentation on making links crawlable is short and strict: Google can reliably follow a link only when it’s an <a> element with an href attribute. A span with a click handler, or a button that changes the route, isn’t a link to a crawler.
The good news is that the framework does the right thing by default. The Next.js <Link> component renders a real <a href>, and Astro components output whatever HTML you write. The risk is in where the link list comes from. A related posts widget that calls an API from the browser adds its links only after the page has loaded. Google renders JavaScript in a second stage, but plenty of tools and crawlers fetch only the HTML, and links that are already in the file don’t depend on any of that. If you’re not sure where your current links come from, I explain how to check whether internal links are in the HTML.
So my rule for internal linking on static and headless sites: decide the links when the site is built, render them on the server, and ship them in the HTML. As a bonus, the same content always produces the same links, which makes changes easy to review.
Three kinds of links you can build automatically

The free code produces three blocks. Each one fixes a different gap.
- Related pages. The top three (or however many you choose) pages most similar to the current one, scored from shared tags, the same category and, if you have them, embeddings. This is the block that stops new posts from becoming orphan pages: every page links out, and every page is someone else’s neighbour. To find the orphans you already have, my blog architecture audit checks click depth and orphan pages from a crawl.
- Where this is mentioned. For every page, the other pages that name it, by title or by other names you list (“k-means” for “K-means clustering for SEO”). Each mention records whether that page already links here. The unlinked ones are the easiest in-body links you’ll ever add.
- Pinned links. Links a person has already reviewed and approved, read from a CSV. They go to the top of the related list, because an editor’s judgement beats a score when you have it.
All three are computed once per build and cached. The page templates only look them up.
How the related-pages score works

I kept the score simple enough to explain in a sentence, because you’ll want to debug it one day. For a source page and a candidate page:
score = (0.5 × tag overlap + 0.2 × same category + 0.3 × cosine similarity) / weights used- Tag overlap is Jaccard similarity: the tags both pages share, divided by all the distinct tags on the two pages. Two pages tagged internal-linking, audits, crawling score 1; pages with one shared tag out of four score 0.25.
- Same category is simply 1 or 0.
- Cosine similarity compares the pages’ embeddings, if you have an embeddings file. Cosine similarity close to 1 means the two texts are about the same thing, even when they use different words. It’s the same comparison behind semantic keyword clustering.
If a page has no embedding, that part and its weight drop out and the rest is rescaled, so the score still runs from 0 to 1. Candidates under 0.1 are never shown, a page never links to itself, and ties go to the newer page and then alphabetically. That last rule matters more than it looks: without it, two equally good candidates can swap places between builds and your diffs fill with noise.
Every chosen link comes back with a reason, such as “shared tags: internal-linking; same category; similarity 0.53”. When someone asks why page A links to page B, you can answer.
What it produces on a real build
Both example sites use the same ten sample posts about ML for SEO topics (embeddings, clustering, internal link audits, orphan pages and so on), an embeddings file made with the small open all-MiniLM-L6-v2 model, and a sample link menu of nine rows. Running the preview script prints this:
Link menu: {"approved":6,"proposed":2,"rejected":1} rows by status; using approved
skipped https://www.example.com/blog/k-means-for-seo/ -> https://www.example.com/courses/clustering/: target_url outside basePath
10 pages, 30 related links (4 pinned from the menu), embeddings: yes
19 mentions, 14 of them not linked yet
WARNING link menu: "topic-clusters" -> "site-architecture-guide" points at a page that is not in this build (skipped)Three things in that output are worth a closer look.
Only approved rows are used. Two proposed rows and one rejected row are counted and left out. Of the six approved rows, four became pinned links. One pointed outside the blog, and one pointed at a page that no longer exists: it was merged after the link was approved. Without that check, the build would have shipped a broken link. With it, the row is skipped and the warning appears in the build log of both Next.js and Astro.
14 of 19 mentions are unlinked. The “What are embeddings?” post is named three times in the keyword clustering post, which doesn’t link to it once. That’s a ready-made list of in-body links for an editor to add in a sentence, where they’re most useful.
The weights shape the result. Here are the three related links the build picked for the “Finding orphan pages” post:
| Position | Target | Score | Why |
|---|---|---|---|
| 1 | Topic clusters and hub pages | 0.26 | pinned: approved in the link menu |
| 2 | How to run an internal link audit | 0.91 | shared tags: internal-linking, audits, crawling; same category; similarity 0.72 |
| 3 | Related posts at build time | 0.48 | shared tags: internal-linking; same category; similarity 0.50 |
The pinned link wins position one despite the lowest score. That’s the point of pinning: “orphan pages are fixed by adding them to their hub” is an editorial connection the tags don’t capture. And look at the k-means post: its embedding similarity to the keyword clustering post is 0.71, the second-highest pair in the set, but they share only one tag and sit in different categories, so the combined score is 0.34. Both are about clustering, so the model sees them as close; the taxonomy files them apart. If your tags are messy and your embeddings are good, give the embedding more weight. If your taxonomy is carefully kept, trust it more.
Next.js: the App Router walkthrough
The Next.js example uses Next.js 16 with the App Router. Four pieces do the work.
- Load and score once.
lib/content.tsreads the Markdown with gray-matter, builds the related index and the mentions index, and caches them in a module variable. Swap the loader for your CMS query and nothing else changes. - Generate every post at build time. The post route exports
generateStaticParamsand setsdynamicParams = false, so the related lists exist for every post when the build finishes. - Render with
next/linkin a server component. No client JavaScript is needed to show the links. - Export static HTML. With
output: 'export',next buildwrites every page toout/. That step is optional (the links render on the server either way), and it makes the result easy to check. More on that in the static exports guide.
The component is short:
export function RelatedPosts({ links }: { links: RelatedLink[] }) {
if (!links.length) return null;
return (
<nav aria-labelledby="related-heading" className="related">
<h2 id="related-heading">Related reading</h2>
<ul>
{links.map((l) => (
<li key={l.slug} data-pinned={l.pinned || undefined}>
<Link href={l.url as Route}>{l.title}</Link>
</li>
))}
</ul>
</nav>
);
}The as Route cast is there because the example switches on typedRoutes, which makes next build type-check every literal href against your real routes. hrefs that come from data can’t be checked that way, so they’re cast. And here’s what lands in out/blog/orphan-pages/index.html after next build:
<nav aria-labelledby="related-heading" class="related"><h2 id="related-heading">Related reading</h2><ul>
<li data-pinned="true"><a href="/blog/topic-clusters/">Topic clusters and hub pages</a></li>
<li><a href="/blog/internal-link-audit/">How to run an internal link audit</a></li>
<li><a href="/blog/related-posts-at-build-time/">Related posts at build time</a></li></ul></nav>Plain links, in the file, before any script runs. That’s what you want a crawler to find. The code itself is on GitHub, with the tests and both examples.
Astro: content collections walkthrough

For Astro SEO the pattern is the same, and Astro makes it a little shorter. The example uses Astro 7 content collections:
src/content.config.tsdefines apostscollection with theglob()loader and a schema for title, date, category, tags and anakalist of other names.src/lib/links.tscallsgetCollection('posts'), maps each entry to a page (the raw Markdown is inentry.body, which the mentions index needs) and builds both indexes once.src/pages/blog/[slug].astrousesgetStaticPaths()andrender()as in the routing guide, then passes the lists to two small components that output<a href>.
If your editors already hand-pick related posts with Astro’s reference() field, keep it: resolve those entries and pass them in as pinned links, and the score fills the remaining slots.
I built both examples from the same content and compared the output: the related links in all ten pages are identical in the Next.js and Astro builds. The scoring lives outside the framework, so moving from one to the other doesn’t change your internal links.
Using a headless CMS instead of Markdown
Nothing in the scoring cares where the content comes from. (For where links live in Contentful, Sanity and Storyblok in the first place, see my guide to headless CMS internal linking.) It needs a slug, a URL and a title for each page, plus whatever you have of tags, category, date, other names and body text. With Contentful, Sanity or Storyblok, the loader becomes a query, and two habits keep the links fresh:
- Rebuild on publish. Related lists are only as fresh as the last build, so trigger a build from your CMS webhook when content changes. If you deploy often, the same pipeline can notify Bing and other engines of changed URLs with IndexNow.
- Make embeddings a separate step.
make_embeddings.pywrites anembeddings.jsonfile. Run it when content changes or as a CI step, and the build only reads the file. Your build never waits on a model, and it never needs an API key.
If you want related links to be editable in the CMS itself, Sanity and Contentful both store references between entries, and the official docs on presenting Portable Text show how links inside rich text are rendered. Writing links back into structured rich text is a different job with more risk, which is where the course comes in (more below).
Limits and pitfalls
- Tags do the heavy lifting. Inconsistent tags (“ml”, “machine-learning”, “Machine Learning”) quietly ruin the score. Clean them first, or lower the tag weight and lean on embeddings.
- Related blocks are template links. They’re good for discovery and for making sure nothing is orphaned. They’re no replacement for a link written in a sentence, where the anchor and the context tell readers why the next page matters. The “where this is mentioned” list exists to help with exactly those.
- Mentions are matched by name. A page with a broad title like “Clustering” will match every sentence that uses the word. Give it a more specific title or exclude it.
- Don’t move the block into the browser later. A redesign that fetches related posts client-side undoes the whole point. Check the built HTML after any template change.
- The score knows similarity, not sequence. For “read this next” in a series, pin the links. And for the hub-and-spoke structure itself, plan it from intent first, as in search intent-first website architecture; the build then keeps it intact.
If you’d like to see more ways to automate this, I compared ten in 10 ways to automate internal linking with AI, including embedding-powered related posts and keeping links healthy over time.
Check the links you ship
Building links automatically means you should check them automatically too. I ran lychee in offline mode on both builds: 92 links in the Next.js output and 75 in the Astro output, all resolving to real files, with no network requests. Astro doesn’t check internal links on its own: in my test, a build with a deliberately broken link completed without a warning. I’ve written up the settings and CI workflow for each generator in stop broken internal links at build time.
What the course adds
This post and the free code cover template links: the related, mentions and pinned blocks. The course AI-powered Internal Linking Audit and Automation, led by Sam Torres, goes further. In Module 5, my guest module on shipping links in your CMS, Lesson 5.7 is an implementation guide for headless and static sites. It covers adding links inside structured rich text without breaking the editor, applying linking rules at build time and reading the preview before anything ships, deciding when a link should be written back to the CMS, the checks to run before any write-back, and recording when links went live so you can measure the change in Module 7. The link menu this code reads is the one you build in Lab 3.8.
Frequently asked questions
Is Next.js good for SEO?
Next.js gives you what search engines need: server-rendered or static HTML, real <a href> links through next/link, and control over metadata. What it doesn’t give you is the content features a CMS like WordPress adds for free, such as related posts. Those you build yourself, and building them at build time keeps them in the HTML.
Does next/link help SEO?
It renders a standard <a href>, which is the kind of link Google says it can follow. It doesn’t add any ranking benefit on top of that. The SEO value comes from which pages you link and how.
How many related links should a page show?
I use three to five. Enough that every page links out to its closest neighbours, few enough that each link is clearly relevant. The n option sets it.
Do I need embeddings?
No. With tags and categories alone the code works, and the embedding weight simply drops out. Embeddings help most when your taxonomy is thin or inconsistent, and the small open model runs on a laptop at no cost.
Is there an Astro SEO plugin for related posts?
You don’t need one. Content collections already give you every entry at build time, so a related list is a few lines of code. The free code does the scoring and leaves the markup to you.
MLforSEO Academy
Pick your learning path
Start with the course that goes deepest on this article, then more courses taught by Lazarina Stoy, most relevant first.
AI-powered Internal Linking Audit and Automation
by Sam Torres with Lazarina Stoy
Audit how your site links to itself, find the pages and entities your links leave out, and plan and automate the fixes with AI at scale.
View course · €350 →Introduction to Machine Learning for SEO
Go from zero to running your first ML workflows for SEO: classification, clustering, entity extraction, fuzzy matching and content transformation.
View course · €250 →Semantic AI-powered SEO Keyword Research
by Lazarina Stoy with Beatrice Gamba
Build a semantic keyword universe and an automated content-brief workflow, from query understanding through SERP analysis to delivery.
View course · €400 →AI Search & LLMs: Entity SEO and Knowledge Graph Strategies for Brands
by Beatrice Gamba with Lazarina Stoy
Win in both traditional Google and LLM-driven search by mastering entities, brand recognition, and knowledge graph integration.
View course · €200 →A complete, repeatable entity audit you can run on any site. Built on the 5Cs of entity representation and demonstrated end to end on a real, unedited site.
View course · €150 →


