Add Reading Time

Create a remark plugin which adds a reading time property to the frontmatter of your Markdown or MDX files. Use this property to display the reading time for each page.

  1. Install Helper Packages

Install these two helper packages:

Terminal window
npm install reading-time mdast-util-to-string

Copied!

  1. Create a remark plugin.

This plugin uses the mdast-util-to-string package to get the Markdown file’s text. This text is then passed to the reading-time package to calculate the reading time in minutes.

remark-reading-time.mjs
import getReadingTime from 'reading-time';
import { toString } from 'mdast-util-to-string';

export function remarkReadingTime() {
  return function (tree, { data }) {
    const textOnPage = toString(tree);
    const readingTime = getReadingTime(textOnPage);
    // readingTime.text will give us minutes read as a friendly string,
    // i.e. "3 min read"
    data.astro.frontmatter.minutesRead = readingTime.text;
  };
}

Copied!

  1. Add the plugin to your config:
astro.config.mjs
import { defineConfig } from 'astro/config';
import { remarkReadingTime } from './remark-reading-time.mjs';

export default defineConfig({
  markdown: {
    remarkPlugins: [remarkReadingTime],
  },
});

Copied!

Now all Markdown documents will have a calculated minutesRead property in their frontmatter.

  1. Display Reading Time

Use the minutesRead frontmatter property from Astro.props to add the reading time to a Markdown layout. The example layout below displays the reading time above the page content:

src/layouts/BlogLayout.astro
---
const { minutesRead } = Astro.props.frontmatter;
---

<html>
  <head>...</head>
  <body>
    <p>{minutesRead}</p>
    <slot />
  </body>
</html>

Copied!


More recipes