🔥 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 Word Count: Count Words in Every Post

Add an Astro word count to posts: count words from post.body with Intl.Segmenter, or add a remark plugin that writes wordCount into each post's frontmatter.

#Astro#Astro Word Count#Content Collections#Markdown

To show a word count in Astro, count the words in post.body, the raw Markdown of each entry, after stripping code blocks and syntax. For counts available everywhere a post is rendered, write a small remark plugin that adds wordCount to the post’s frontmatter, then read it from remarkPluginFrontmatter. Both run at build time.

Key Takeaways

  • post.body gives you the Markdown source; strip code and markup before counting.
  • Intl.Segmenter with granularity: 'word' counts words correctly in languages without spaces.
  • A remark plugin counts the parsed text, so syntax never inflates the number.
  • The same count gives you reading time: divide by about 200 to 250 words per minute.

Count from post.body

// src/lib/word-count.ts
const segmenter = new Intl.Segmenter('en', { granularity: 'word' });

export function wordCount(markdown = '') {
  const text = markdown
    .replace(/```[\s\S]*?```/g, ' ')         // fenced code
    .replace(/<[^>]+>/g, ' ')                // HTML and MDX components
    .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1') // links and images -> text
    .replace(/^import\s.+$/gm, ' ');         // MDX imports
  let count = 0;
  for (const part of segmenter.segment(text)) {
    if (part.isWordLike) count++;
  }
  return count;
}
---
// src/pages/blog/[id].astro (excerpt)
import { wordCount } from '../../lib/word-count';
const { post } = Astro.props;
const words = wordCount(post.body);
---
<p>{words.toLocaleString('en-US')} words</p>

Intl.Segmenter is built into Node.js and modern browsers. Its isWordLike flag skips punctuation and whitespace, and it handles Chinese, Japanese and Thai, where splitting on spaces gives nonsense. Pass the post’s language instead of 'en' on a multilingual site. Whether code counts as words is your call; most writers leave it out.

Because this works on any entry with a body, you can also use it on listing pages or to sort posts by length.

Count with a remark plugin

A remark plugin sees the parsed Markdown tree, so headings, emphasis and links are already plain text:

// src/markdown/remark-word-count.mjs
import { toString } from 'mdast-util-to-string';

export function remarkWordCount() {
  const segmenter = new Intl.Segmenter('en', { granularity: 'word' });
  return (tree, file) => {
    const prose = { ...tree, children: tree.children.filter((n) => n.type !== 'code') };
    let count = 0;
    for (const part of segmenter.segment(toString(prose))) if (part.isWordLike) count++;
    file.data.astro.frontmatter.wordCount = count;
  };
}
// astro.config.mjs
import { defineConfig } from 'astro/config';
import { unified } from '@astrojs/markdown-remark';
import { remarkWordCount } from './src/markdown/remark-word-count.mjs';

export default defineConfig({
  markdown: {
    processor: unified({ remarkPlugins: [remarkWordCount] }),
  },
});

Install @astrojs/markdown-remark and mdast-util-to-string. Remark plugins need the unified() processor because Astro 7’s default Sätteri processor runs its own plugin format. MDX inherits the plugin. Read the value after rendering:

---
import { render } from 'astro:content';
const { Content, remarkPluginFrontmatter } = await render(post);
---
<p>{remarkPluginFrontmatter.wordCount} words</p>

The top-level filter drops fenced code blocks; nested ones inside lists are still counted. The custom remark plugin tip explains the plugin shape in more detail.

Which to use

post.body helper Remark plugin
Works on listing pages without rendering Yes No, needs render()
Accuracy Good (regex cleanup) Better (parsed tree)
Processor requirement None unified()

For reading time, divide the count by a words-per-minute figure and round up; the reading time tip does exactly that. Word counts are also handy in editorial checks, for example warning in CI when a post is under a minimum length. The Content Collections docs page covers post.body and entry fields. If you run a blog or magazine theme, add the count next to the date in the post header.

FAQ

How do I count words in an Astro Markdown post?

Use post.body, the raw Markdown from the content collection, remove code blocks and markup, then count with Intl.Segmenter and its isWordLike flag. Or add a remark plugin that stores wordCount in the post’s frontmatter.

Why is my word count too high?

You’re probably counting code blocks, URLs or MDX import lines. Strip fenced code, link targets, HTML and import statements before counting, or count from the parsed tree in a remark plugin.

Does counting words slow down the Astro build?

Barely. Counting runs once per post at build time and takes milliseconds even for long articles. Nothing is added to the JavaScript sent to visitors.