Duong Hoang Nam

Search Articles

Find AI, technology, and programming guides

Press Esc to closeFull Search Page →
Tutorials

How to Build Related Posts in Astro with Content Collections and Tags (2026 Guide)

Learn to build related posts in Astro using Content Collections, tags, relevance scoring, and reusable components with SEO-friendly internal links.

By Duong Hoang Nam
How to Build Related Posts in Astro with Content Collections and Tags (2026 Guide)

A visitor finishes reading a tutorial about improving Astro SEO. What should they read next?

A random post from your archive might be recent, but it may not help them solve the next problem. A thoughtful Related Articles section can recommend content about the same tools, concepts, or workflow, giving readers useful next steps without requiring an editor to update every article manually.

In this guide, we’ll build a lightweight related-posts system for an Astro blog using Content Collections, tags, categories, and deterministic relevance scoring. The recommendations are rendered as ordinary HTML links at build time—no recommendation SaaS, client-side ranking library, database, or tracking script required.

The examples assume a Git-backed blog edited through Decap CMS and generated by modern Astro Content Collections. Adapt the field names, content loader, and URL helper to your existing project; this is a reference implementation, not code claimed to be running on this website.

As a blog grows, internal navigation becomes harder to maintain. You can manually add links to every article, but those links may become outdated when new tutorials are published.

Related posts provide a repeatable way to:

  • Offer a genuinely useful next read based on the article’s topic.
  • Expose older, still-relevant tutorials that are otherwise buried in archives.
  • Keep related article recommendations up to date as content changes.
  • Add crawlable internal links without relying on browser-side JavaScript.
  • Avoid maintaining a hand-written list at the bottom of every post.

However, this is not a ranking shortcut. Google recommends relevant internal links with descriptive anchor text, but does not promise that a related-post component will increase rankings or engagement. The recommendations are only as good as your metadata and editorial decisions.

Official reference: Google Search Central — Link best practices.

We will use a simple build-time pipeline:

  1. Load blog entries from Astro’s blog collection.
  2. Exclude drafts, future-dated entries, and the article currently being viewed.
  3. Normalize editor-provided tags.
  4. Rank candidates using shared tags and a category bonus.
  5. Resolve an article URL and render up to three links in an accessible list.

Diagram showing a five-step Astro related-posts pipeline: loading blog entries, filtering drafts, normalizing tags, scoring relevance, and rendering related links

Figure 1: A build-time selection pipeline keeps recommendations relevant, deterministic, and free from browser-side ranking code.

There are two important boundaries:

Content filtering is a publishing rule. A draft should not become publicly discoverable just because its metadata matches another article.

URL generation is a routing rule. Astro’s collection id is often derived from the source filename, but your production URL may use an explicit CMS slug or another route map. Never assume every project can convert an ID directly to a public URL.

3. Project Prerequisites

You will need:

  • A working Astro site with a blog Content Collection.
  • Markdown articles with titles and publication dates.
  • A blog detail page or layout where the component can be inserted.
  • Optional tags and category frontmatter fields.
  • A safe branch or development environment for testing.

This tutorial uses Astro’s build-time getCollection() API. It is not designed for live collections or per-request recommendations from an external content API.

For a new project, Astro documents content collections under src/content.config.ts. Existing projects may already have a different folder path and custom schema—merge fields rather than replace your current configuration.

Official reference: Astro — Content Collections.

4. Define Consistent Tags and Categories in Decap CMS

For a related-post algorithm, consistency matters more than having many tags. If editors use JavaScript, javascript, and JS for the same topic, you may get inconsistent matches unless you normalize or map them.

A practical naming approach for a technical blog is:

Metadata Example Purpose
Category Tutorials Broad section of the website
Tag astro Framework used in the article
Tag content-collections Specific feature covered
Tag decap-cms Relevant publishing tool
Tag seo Wider problem or discipline

Example Markdown frontmatter:

---
title: "Astro SEO: A Practical Guide"
description: "Improve metadata, links, and indexing in Astro."
pubDate: 2026-10-21
category: "Tutorials"
tags:
  - astro
  - seo
  - content-collections
draft: false
---

In Decap CMS, a list field can make tags editable without asking the author to type YAML manually. Add fields similar to the following inside your existing blog collection field definitions:

- label: "Tags"
  name: "tags"
  widget: "list"
  required: false
  default: []
  field:
    label: "Tag"
    name: "tag"
    widget: "string"

This snippet is a field fragment, not a replacement for your whole config.yml. Your CMS may already have a tag widget, a taxonomy, or a different output shape. Inspect saved frontmatter before changing it.

Don’t create tags solely for the algorithm

A tag should describe something meaningful in the article. If every post carries the same broad technology tag, that tag alone provides little evidence of relevance.

Consider limiting authors to a manageable vocabulary and reviewing tags periodically.

5. Add the Fields to Your Existing Astro Schema

In a modern Astro Content Collection, the schema describes which fields are available in entry.data. For example:

// src/content.config.ts — illustration, not a drop-in replacement
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const blog = defineCollection({
  loader: glob({
    pattern: '**/*.md',
    base: './src/content/blog',
  }),
  schema: z.object({
    title: z.string().min(1),
    description: z.string().min(1),
    pubDate: z.coerce.date(),
    draft: z.boolean().default(false),
    category: z.string().optional(),
    tags: z.array(z.string()).default([]),
  }),
});

export const collections = { blog };

Notice the z import from astro/zod in current Astro documentation. The glob() loader path is an example; match the directory where your CMS actually commits Markdown files.

Also preserve all existing fields such as featuredImage, author information, canonical URL, updatedDate, or other metadata. Removing them from the schema or changing their types can break existing templates.

6. Query the Blog Collection

Astro’s getCollection() returns entries from a named collection, including their unique id and parsed data.

import { getCollection } from 'astro:content';

const posts = await getCollection('blog');

You can optionally filter at query time:

const now = new Date();
const publishedPosts = await getCollection('blog', ({ data }) =>
  data.draft !== true && data.pubDate.getTime() <= now.getTime(),
);

The second check excludes scheduled posts whose publication date is still in the future. It assumes your pubDate schema produces a valid Date, as the schema in section 5 does.

Do not infer that a Decap CMS editorial draft is necessarily loaded into every production build. The exact set of files depends on your branch and publishing workflow. Nevertheless, applying publication filters in the recommendation function is a useful additional safeguard.

7. Choose an Explainable Relevance Formula

A simple weighted score is easier to debug than an opaque recommendation system.

For this tutorial:

Relevance score = (shared tag count × 4) + (same category ? 2 : 0)

Examples:

Candidate Shared tags Same category Score
Core Web Vitals in Astro 2 Yes 10
Astro Metadata Guide 2 Yes 10
General SEO Guide 1 Yes 6
Unrelated Cooking Article 0 No 0

Only candidates with a positive score are shown. Ties are resolved by most recent publication date, followed by the stable content ID.

Diagram comparing shared tags and relevance scores for three candidate Astro blog posts

Figure 2: Shared topic tags carry more weight than a broad category match, while deterministic tie-breaking keeps builds predictable.

These weights are editorial defaults, not scientifically proven engagement coefficients. Measure and refine them when you have enough real content and user feedback.

Create src/lib/related-posts.ts. This example uses the typed Astro collection entry and intentionally avoids browser APIs.

import type { CollectionEntry } from 'astro:content';

type BlogPost = CollectionEntry<'blog'>;

function normalizedTags(tags: string[] | undefined): Set<string> {
  return new Set(
    (tags ?? [])
      .map((tag) => tag.trim().toLocaleLowerCase('en'))
      .filter(Boolean),
  );
}

function publishedAt(post: BlogPost): number {
  return new Date(post.data.pubDate).getTime();
}

function published(post: BlogPost, now: Date): boolean {
  const time = publishedAt(post);
  return post.data.draft !== true &&
    Number.isFinite(time) && time <= now.getTime();
}

export function findRelatedPosts(
  current: BlogPost,
  candidates: BlogPost[],
  limit = 3,
  now = new Date(),
): BlogPost[] {
  if (!Number.isInteger(limit) || limit <= 0) return [];

  const tags = normalizedTags(current.data.tags);
  const category = (current.data.category ?? '')
    .trim().toLocaleLowerCase('en');

  return candidates
    .filter((post) => post.id !== current.id && published(post, now))
    .map((post) => {
      const matchingTags = [...normalizedTags(post.data.tags)]
        .filter((tag) => tags.has(tag)).length;

      const sameCategory = Boolean(category) &&
        (post.data.category ?? '')
          .trim().toLocaleLowerCase('en') === category;

      return {
        post,
        score: matchingTags * 4 + (sameCategory ? 2 : 0),
      };
    })
    .filter(({ score }) => score > 0)
    .sort((a, b) =>
      b.score - a.score ||
      publishedAt(b.post) - publishedAt(a.post) ||
      a.post.id.localeCompare(b.post.id, 'en'),
    )
    .slice(0, limit)
    .map(({ post }) => post);
}

Why this implementation is safer

The current entry is removed by ID, not title. Two distinct posts can legitimately share a title.

Tags are compared in a normalized form without modifying saved CMS content. Each tag counts once thanks to Set.

Draft and future entries are excluded even if the caller accidentally supplies them.

The final sort is stable in effect: score, date, and ID determine the displayed order. We do not rely on Astro’s collection iteration order, which should not be assumed to be stable.

What this code does not do

It does not compute semantic similarity from the full article body, detect content quality, understand synonyms, or guarantee that two posts offer genuinely complementary information. It is an explainable metadata-based heuristic.

If your schema stores tags as objects rather than strings, convert them to strings before calling normalizedTags(). If you have multilingual tags, consider language-aware normalization and aliases.

9. Build a Reusable RelatedPosts.astro Component

Create src/components/RelatedPosts.astro:

---
import type { CollectionEntry } from 'astro:content';
import { findRelatedPosts } from '../lib/related-posts';

interface Props {
  current: CollectionEntry<'blog'>;
  posts: CollectionEntry<'blog'>[];
  limit?: number;
}

const { current, posts, limit = 3 } = Astro.props;
const related = findRelatedPosts(current, posts, limit);

// Adapt this helper if your site's public slug is not entry.id.
const articleUrl = (post: CollectionEntry<'blog'>) =>
  `/blog/${encodeURIComponent(post.id)}/`;
---

{related.length > 0 && (
  <aside aria-labelledby="related-posts-heading" class="related-posts">
    <h2 id="related-posts-heading">Related articles</h2>
    <ul>
      {related.map((post) => (
        <li>
          <a href={articleUrl(post)}>{post.data.title}</a>
          <p>{post.data.description}</p>
        </li>
      ))}
    </ul>
  </aside>
)}

You can style the section using your current Tailwind design system or scoped Astro CSS. The key accessibility features are native links, a clear heading, a list structure, and visible keyboard focus.

Important: verify slug mapping

The URL helper above works only for projects where the collection entry ID equals the public article slug and does not contain nested path separators.

If your CMS uses a dedicated slug field or your router transforms IDs, reuse the same URL helper used in the main blog listing and getStaticPaths(). Never generate links by guessing a slug from the article title.

For a blog with folders under the content directory, encode each URL path segment separately rather than encoding the entire nested path as one segment.

10. Insert Related Posts Into the Existing Article Layout

Place the component after the article body and before less-related page elements such as the global footer. This makes the recommendations discoverable without interrupting reading.

A simplified pattern inside your existing blog route or layout is:

---
import { getCollection } from 'astro:content';
import RelatedPosts from '../../components/RelatedPosts.astro';

// `entry` represents the current post already loaded by your route.
const entry = Astro.props.entry;
const blogPosts = await getCollection('blog');
---

<!-- Keep your current title, metadata and article rendering. -->
<RelatedPosts current={entry} posts={blogPosts} limit={3} />

This snippet is intentionally not a full replacement for your existing [slug].astro or blog layout. Your route may load entries through a different file, pass different props, or already render related links.

Before adding the component, inspect the actual template and remove any duplicate recommendations if they already exist.

11. What If an Article Has No Useful Matches?

Sometimes a new article has unusual tags or is the only post in its category.

You have three reasonable choices:

  1. Show no related-post section until genuinely related content exists.
  2. Offer a separately labeled “Latest articles” section.
  3. Let an editor manually choose related articles for an important page.

The implementation above chooses the first option: it renders nothing when related.length === 0.

This is preferable to presenting unrelated articles under a misleading “Related” heading. You can add a fallback later, but label it accurately.

For cornerstone content, consider an optional manual override through Decap CMS. Editorial relevance may be more valuable than a minor algorithmic score difference.

12. How Much JavaScript Does This Add?

The related-post ranking runs during Astro’s page generation when used in prerendered article routes. The component emits ordinary HTML containing anchors, headings, and text.

That means the basic implementation adds no client-side recommendation JavaScript. Visitors do not need an API call or third-party personalization service for the links to appear.

It does add some build-time work. For a small blog with dozens or a few hundred entries, this is usually simple enough. For very large collections, loading and scoring the full collection on each page may become inefficient. Precompute a relationship map once during the build or create a cached index if profiling demonstrates a real problem.

Avoid claiming a guaranteed PageSpeed improvement just because this implementation is static. The final result still depends on the entire page, images, CSS, scripts, and hosting behavior.

13. Avoid Common SEO and Editorial Mistakes

Mistake: Every post uses the same tags. If all articles use only technology, recommendations become nearly arbitrary. Choose more specific topical tags.

Mistake: Linking to drafts. Filtering only by a shared tag can accidentally reveal unpublished URLs. Apply publication rules consistently in the main route, list pages, RSS feed, and related-post component.

Mistake: Inventing article URLs. Collection IDs, filenames, and public slugs can differ. Reuse your production URL logic and test the rendered href values.

Mistake: Over-optimizing anchor text. Use the actual descriptive article title. Avoid repetitive keyword-stuffed anchor text or deceptive labels.

Mistake: Making every link open a new tab. Ordinary related articles normally belong to the same browsing experience; use standard links without target="_blank".

Mistake: Duplicating existing blocks. If the page already has a manually curated Continue Reading section, decide whether related recommendations should replace it, complement it, or appear elsewhere.

14. Test the Recommendations Before Publishing

Create a small sample of entries and verify expected behavior:

Test Expected result
Two posts share two tags Higher score than one shared tag
Another post is a draft Never appears
Another post has a future publication date Never appears
Candidate equals current entry Never appears
Candidate shares no tags or category Not labeled as related
Two candidates have the same score Newer post wins; ID breaks remaining ties
No valid related posts exist Component does not render an empty heading
CMS changes a public slug Link mapping still matches real published route
Browser keyboard navigation Every link can receive visible focus
Site generated for production No related link points to a missing page

You can also run the project’s existing broken-link checker against the built dist/ directory after adding this component.

Pre-publish checklist for Astro related posts including drafts, self-links, URL mapping, tag normalization, accessibility, and empty states

Figure 3: Validate both recommendation quality and the reliability of the resulting links before deploying.

15. Test the Output on Real Article Pages

Build the site with the same command used in deployment:

npm ci
npm run build

Then preview the generated site with your project’s normal preview workflow. Select representative pages:

  • An Astro tutorial with several closely related articles.
  • A category with only one published article.
  • A post whose tag casing differs from other entries.
  • A page with a long title and a narrow mobile viewport.
  • An article that previously changed its public slug.

Use browser inspection to confirm that the href values actually point to published article pages. A syntactically correct link is not necessarily a working production link.

For an automated link-checking workflow, read our guide to detecting broken Astro links with GitHub Actions.

If you have privacy-respecting analytics configured, you can measure whether users open related articles, which suggested topics attract attention, and whether new recommendations improve navigation.

Suggested measurements:

Measurement What to look for
Related-post clicks Are users opening the next relevant tutorial?
Links with zero engagement Are titles unclear or suggestions weak?
Repeat suggestions Do the same few posts dominate too many pages?
Broken-link rate Does CMS publishing preserve valid related URLs?
Editorial reviews Are the top three suggestions actually useful?

Do not treat a click as proof of content quality or claim an increase in search traffic without evidence. Compare results over time and consider seasonal changes, search traffic mix, and which articles visitors start from.

For websites that load analytics only after consent, preserve that behavior. The related-post component itself does not need to track users.

17. Frequently Asked Questions

Yes. Astro’s Content Collections and a small ranking function are enough for a static, tag-based recommendation section.

Should I use categories or tags?

Use both if the metadata is well maintained. Tags provide finer topic signals; a category can be a useful secondary signal. Neither should be treated as a substitute for editorial judgment.

Will this feature improve SEO rankings?

There is no guaranteed ranking improvement. Useful internal links make relevant content easier to discover, but results depend on content quality, site structure, crawlability, and many other factors.

Can Decap CMS control the recommendations?

Yes. Editors can manage tags and categories in frontmatter. You can also add a manual override field for specific articles if your publishing workflow needs it.

It can if you omit filtering or if your route and CMS publication states differ. Exclude draft and future entries and verify that public URLs really exist.

Does it work with Astro 7?

The examples follow the modern build-time Content Collections model and Astro’s documented getCollection() API. You must still adapt field names, types, paths, and routes to your project; the code has not been tested inside every Astro version or repository.

Should related-post recommendations be identical for every visitor?

For a documentation or tutorial blog, deterministic static recommendations are often sufficient. Personalization introduces additional complexity and data/privacy considerations that may not be justified.

18. Final Thoughts

Related posts work best when they help readers continue a meaningful learning journey—not when they simply add more links to a page.

With Astro Content Collections and consistent CMS tags, you can build a transparent, lightweight recommendation system that updates during each website build. Its safety comes from filtering drafts, honoring the actual URL scheme, and using accessible HTML rather than hidden client-side behavior.

Start with a simple scoring formula, verify real pages, and refine the recommendations based on editorial judgment and measured reader needs.

Better internal linking begins with better content relationships—not more links.


Continue Reading

Official References

Technical disclosure: This tutorial provides a reference implementation. The complete code has not been deployed to the production repository. Verify your actual CMS field definitions, Astro schema, routing rules, publishing workflow, and generated links before enabling it on a live website.

About the Author

Duong Hoang Nam

Duong Hoang Nam

Software engineer sharing practical tutorials, real-world experiments, and insights on AI tools, automation, and web development.

Read My Story →

Related Articles