Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Content Collections and Markdown

Rendering Entries, MDX and Markdown Plugins

Render collection entries with render(), build a table of contents from headings, map MDX components and extend Markdown with remark and rehype plugins.

Querying a collection gives you data. To show the body of a Markdown or MDX entry as HTML, you call render(). This lesson covers what render() returns, how to build a table of contents, how to extend the Markdown pipeline with remark and rehype plugins and how to use MDX with your own components.

render()

Import render from astro:content and pass an entry. It returns an object with two useful parts: a Content component and a list of headings.

ASTRO
---
import { getEntry, render } from "astro:content";

const post = await getEntry("blog", "first-post");
const { Content, headings } = await render(post);
---
<article>
  <h1>{post.data.title}</h1>
  <Content />
</article>

<Content /> is an ordinary component that outputs the rendered HTML. You can wrap it in any markup, add classes to the wrapper for typography styles and place it anywhere in your layout. Rendering is cached, so calling it from several places is cheap.

A table of contents from headings

headings is an array of objects with depth (1 to 6), slug (the generated id) and text. Use it to list the sections of long articles:

ASTRO
---
const { Content, headings } = await render(post);
const toc = headings.filter((h) => h.depth === 2 || h.depth === 3);
---
<nav aria-label="On this page">
  <ul>
    {toc.map((h) => (
      <li style={{ marginLeft: `${(h.depth - 2) * 1}rem` }}>
        <a href={`#${h.slug}`}>{h.text}</a>
      </li>
    ))}
  </ul>
</nav>

Because Astro adds id attributes to every heading, these fragment links work without more setup. To add clickable anchor icons beside each heading you use a rehype plugin such as rehype-autolink-headings.

From entry to page

Entry Markdown body and data
render() Runs the Markdown pipeline
1 / 2

The Markdown pipeline: remark and rehype

Astro converts Markdown in two stages:

  1. remark parses Markdown into a tree and lets plugins change the Markdown tree (mdast). Remark plugins add syntax, transform links or compute data.
  2. rehype turns that into HTML and lets plugins change the HTML tree (hast): add attributes, wrap tables, add heading links.

You register plugins in the config:

JavaScript
// astro.config.mjs
import { defineConfig } from "astro/config";
import remarkToc from "remark-toc";
import rehypeSlug from "rehype-slug";
import rehypeAutolinkHeadings from "rehype-autolink-headings";
import { remarkReadingTime } from "./src/plugins/remark-reading-time.mjs";

export default defineConfig({
  markdown: {
    remarkPlugins: [remarkReadingTime, [remarkToc, { heading: "contents" }]],
    rehypePlugins: [rehypeSlug, [rehypeAutolinkHeadings, { behavior: "wrap" }]],
  },
});

A plugin is a function that returns a transformer. Here is a small remark plugin that computes reading time and stores it in the frontmatter for pages and layouts to use:

JavaScript
// src/plugins/remark-reading-time.mjs
import { toString } from "mdast-util-to-string";
import getReadingTime from "reading-time";

export function remarkReadingTime() {
  return function (tree, { data }) {
    const text = toString(tree);
    const minutes = getReadingTime(text).text;   // for example "3 min read"
    data.astro.frontmatter.minutesRead = minutes;
  };
}

For Markdown pages in src/pages/, the new field appears in frontmatter.minutesRead. For collection entries rendered with render(), the plugin result is available from the returned remarkPluginFrontmatter object:

ASTRO
---
const { Content, remarkPluginFrontmatter } = await render(post);
---
<p>{remarkPluginFrontmatter.minutesRead}</p>

MDX and component mapping

MDX lets authors import components inside prose. You can also replace the default elements by passing a components prop to <Content />. This styles or enhances every heading, link or code block:

ASTRO
---
import { render } from "astro:content";
import Heading from "../components/Heading.astro";
import Callout from "../components/Callout.astro";

const { Content } = await render(post);
---
<Content components={{ h2: Heading, Callout }} />

Now every ## in an MDX entry renders through Heading, and <Callout> can be used without an import in the MDX file. Note that this works for .mdx entries, not for plain .md.

MDX
## A section

<Callout type="tip">Short advice appears here.</Callout>

Stand-in: collecting headings

The headings list is a by-product of rendering. This stand-in parses Markdown headings, builds slugs (with a counter for duplicates) and renders a nested table of contents.

Node.js Stand-in: headings and table of contents

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Stand-in: a remark-style plugin pipeline

Plugins are functions that receive a tree and a shared data object, run in order, and can add to the frontmatter. This stand-in builds a mini pipeline with a reading-time plugin and a "wrap tables" step.

Node.js Stand-in: transformer pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Tips

  • Use getHeadings-style data to build a sticky table of contents with IntersectionObserver highlighting.
  • Prefer rehype/remark plugins for site-wide behaviour (links, images, callouts) rather than editing every article.
  • Keep the plugin count small: each plugin runs on every Markdown file at build time.
  • If render() returns an unexpected component or no headings, check that the entry actually has a body (for loaders that return plain data, there is nothing to render).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does render(entry) return?

    render gives a Content component, the heading list and any frontmatter your remark plugins added.
  2. 2. What is the difference between remark and rehype plugins?

    Markdown is first parsed by remark; the resulting HTML tree is then processed by rehype.
  3. 3. How do you replace every h2 in an MDX entry with your own component?

    The components prop maps element names (and custom tags) to components for MDX content.
  4. 4. Where does a table of contents get its data?

    headings lists each heading's depth, slug and text.

Summary

  • render(entry) returns Content, headings and remarkPluginFrontmatter.
  • Build tables of contents from headings and link to the generated slugs.
  • Remark plugins transform the Markdown tree; rehype plugins transform the HTML tree; both are listed in the markdown config.
  • Plugins can add data to frontmatter, such as reading time.
  • MDX entries can map elements and components through the components prop.

Next: Scoped Styles and Global CSS in Astro