🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Content & MDX••By Komal Nakrani

Astro Excerpt: Post Summaries for Listing Pages

Show an Astro excerpt on blog listings: use a description field, split at a more marker, or build a plain-text excerpt from post.body with a small helper.

#Astro#Astro Excerpt#Content Collections#Markdown

The most reliable Astro excerpt is a description field in each post’s frontmatter, validated by your collection schema and shown on listing pages. When you’d rather not write one, generate it: take post.body (the raw Markdown), strip the Markdown syntax, and cut it at a word boundary, or split the body at a <!-- more --> marker.

Key Takeaways

  • A hand-written description doubles as your meta description and is the best excerpt.
  • post.body holds the raw Markdown of glob() entries, which you can turn into plain text.
  • Strip code blocks, images, links and headings before truncating.
  • Make the schema field optional and fall back to a generated excerpt.

Option 1: a description field

// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';

const blog = defineCollection({
  loader: glob({ pattern: '**/*.{md,mdx}', base: './src/content/blog' }),
  schema: z.object({
    title: z.string(),
    description: z.string().max(200).optional(),
    pubDate: z.coerce.date(),
  }),
});

export const collections = { blog };

A short summary written by a person reads better than any truncated paragraph, and you can reuse it for <meta name="description"> and RSS items. The max(200) limit keeps cards a consistent height. Our Zod frontmatter guide covers schema rules like this.

Option 2: generate one from the body

For posts without a description, build a plain-text excerpt from the raw Markdown:

// src/lib/excerpt.ts
export function excerpt(markdown = '', maxLength = 160) {
  const text = markdown
    .replace(/^import\s.+$/gm, '')            // MDX imports
    .replace(/```[\s\S]*?```/g, '')           // fenced code
    .replace(/<[^>]+>/g, '')                  // HTML and components
    .replace(/!\[[^\]]*\]\([^)]*\)/g, '')     // images
    .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')  // links -> text
    .replace(/^#{1,6}\s+.*$/gm, '')           // headings
    .replace(/^>\s?/gm, '')                   // blockquote markers
    .replace(/[*_`~]/g, '')                   // emphasis and inline code
    .replace(/\s+/g, ' ')
    .trim();

  if (text.length <= maxLength) return text;
  const cut = text.slice(0, maxLength);
  return `${cut.slice(0, cut.lastIndexOf(' '))}...`;
}

Use it on the listing page:

---
// src/pages/blog/index.astro
import { getCollection } from 'astro:content';
import { excerpt } from '../../lib/excerpt';

const posts = (await getCollection('blog')).sort(
  (a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf(),
);
---
<ul>
  {posts.map((post) => (
    <li>
      <a href={`/blog/${post.id}/`}>{post.data.title}</a>
      <p>{post.data.description ?? excerpt(post.body)}</p>
    </li>
  ))}
</ul>

post.body is the file content after the frontmatter, available on entries from the glob() loader. Remote loaders may not set it, so the helper defaults to an empty string. Headings are removed because the first heading usually repeats the title. This is regex cleanup, not a Markdown parser, so it’s good enough for summaries but not for rendering.

Option 3: a more marker

Some writers prefer to choose the cut point themselves, as on WordPress:

Astro builds static HTML by default, which is why it's quick.

<!-- more -->

The rest of the post...
// src/lib/excerpt.ts (continued)
export function excerptBeforeMore(markdown = '') {
  const [before, rest] = markdown.split('<!-- more -->');
  return rest === undefined ? null : excerpt(before, 1000);
}

Return null when there’s no marker so the page can fall back to the description or the automatic excerpt. In .mdx files, use {/* more */} instead, because MDX doesn’t allow HTML comments, and split on that string.

Rendered excerpts

All of these produce plain text, which is what listing cards and meta tags need. If you want the excerpt with formatting, store it as a short Markdown field and render it with your loader’s renderMarkdown(), or see the render a Markdown string tip. For more listing-page features, see the featured posts tip and the Content Collections docs page. Most blog themes already render a description on their cards, so Option 1 slots straight in.

FAQ

How do I show a post excerpt in Astro?

Add a description field to your collection schema and render post.data.description on listing pages. For posts without one, generate a plain-text excerpt from post.body by stripping Markdown syntax and truncating at a word boundary.

Does Astro have a built-in excerpt feature?

No. Astro gives you the frontmatter (post.data) and the raw Markdown (post.body) of each entry, and you choose how to build the summary. A description field is the most common approach.

Should the excerpt and meta description be the same?

They can be. A 150 to 160 character summary works for both listing cards and search snippets, and writing it once keeps them consistent.