JONAS RODEHORST

How to Calculate Estimated Reading Time with Contentlayer
8. März 2023

How to Calculate Estimated Reading Time with Contentlayer

Contentlayer
Reading Time

Add reating time as computed field

To calculate the reading time with contentlayer you can use the computedFields in your DocumentType.

contentlayer.config.js
export const Post = defineDocumentType(() => ({
  name: "Post",
  filePathPattern: `**/*.mdx`,
  contentType: "mdx",
  fields: {
    computedFields: {
      readTimeMinutes: {
        type: "number",
        resolve: (doc) => calculateReadingTime(doc.body.raw),
      },
    },
  },
}));

Create the calculateReadingTime function

contentlayer.config.js
export const calculateReadingTime = (text) => {
  // Step 2: Determine the average reading speed (words per minute)
  const wordsPerMinute = 200;
  // Step 3: Calculate the word count
  const noOfWords = text.split(/\s/g).length;
  // Step 4: Calculate the estimated reading time (in minutes)
  const minutes = noOfWords / wordsPerMinute;
  const readTime = Math.ceil(minutes);
  // Step 5: Format the output
  return `${readTime} min read`;
};
  1. Define the function: First, define a function that will calculate the estimated reading time. You can name the function anything you like, but for the purposes of this guide, we'll call it calculateReadingTime.

  2. Determine the average reading speed: The estimated reading time will depend on the average reading speed of your audience. According to research, the average adult reads at a speed of about 200-250 words per minute. can use this value as a baseline for your calculations.

  3. Calculate the word count: Before you can calculate the estimated reading time, you need to determine the word count of the text that you want to analyze. You can do this using the JavaScript "split" method, which will split the text into an array of words, and then use the "length" property to count the number of words.

  4. Calculate the estimated reading time: Once you have the word count and the average reading speed, you can calculate the estimated reading time by dividing the word count by the reading speed. This will give you the estimated reading time in minutes.

  5. Format the output: Finally, you can format the output to display the estimated reading time in a user-friendly way. You might choose to round the estimated reading time to the nearest minute, or display it as a range (e.g. "2-3 minutes").

Display the reading time on your website

Now you can display the reading time on your website by using the readTime field.

import { useDocument } from "contentlayer/source-files";
import { Post } from "../types";
 
export default function PostPage() {
  const post =
    useDocument <
    Post >
    (({ document }) => document.filePath === "/blog/my-first-post.mdx");
 
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.readTime}</p>
    </div>
  );
}
```import { BlogPostHeader } from "@/components/BlogPostHeader";