All Posts
Dec 30, 2024

Adding Categories to the NextJs Markdown Blog

A step by step tutorial on adding categories to a markdown blog created using NextJs 15 using app router.

Featured image for Adding Categories to the NextJs Markdown Blog

Introduction

  • In this article we will primarily focus on adding categories to a markdown blog created using NextJs.
  • Here we already have a step by step article that explains process of creating a markdown blog using the latest version of NextJs and app router.
  • This current article is a continuation of the linked article.

Goal of this article

  1. To have one or more categories assigned to a markdown Blog post.
  2. To be able to filter the articles based on the category selected.
  3. To create a Categories Listing page where we display unique categories, linking to their respective Category page.
  4. On the Category page, we will have a Blog listing of articles filtered by that category.

Quick Recap

  • In the previous article, we see that a category is assigned to an markdown blog post using the front matter.
  • For every article we define the front matter that looks like this:
---
title: "First Blog Post"
category: "general"
date: "2024-12-25"
description: "An introduction to markdown blogs."
image: "/image.jpg" ---

Notice that there is only a single category and it is a string.

Change the front matter of all Blog Posts to accept one or more categories

As a first step Let's

  • Update the font matter of all blog posts to have one or more categories
  • Change the name from category to categories as we will accept one or more categories.
  • Change it's type from string to array. So it should look like this:
---
title: "First Blog Post"
categories: ["category1", "category2", ...] // Enter one or more categories here
date: "2024-12-25"
description: "An introduction to markdown blogs."
image: "/image.jpg" ---

Update Helper functions

Modify the getPostMetaData function to handle multiple categories.

Update getPostMetaData function:

import path from 'path'
import matter from 'gray-matter'
import { v4 as uuidv4 } from 'uuid';
// get the directory of blog posts with markdown files
export const postsDirectory = path.join(process.cwd(), 'articles')
export const getPostMetaData = () => {
const files = fs.readdirSync(postsDirectory)
const markdownFiles = files.filter((file) => file.endsWith('.md'))
const posts = markdownFiles.map((filename) => {
const fileContents = fs.readFileSync(`${postsDirectory}/${filename}`, 'utf-8')
const metaInfos = matter(fileContents)
return {
id: uuidv4(),
slug: filename.replace('.md', ''),
...metaInfos.data,
categories: Array.isArray(metaInfos.data.categories) ? metaInfos.data.categories : [metaInfos.data.categories]
}
})
return posts
}

Create a Function to Fetch Unique Categories

Add a function in /lib/articles.js file to fetch all unique categories

export const getAllCategories = () => {
const posts = getPostMetaData()
const categories = posts.reduce((acc, post) => {
post.categories.forEach((category) => {
if (!acc.includes(category)) {
acc.push(category)
}
})
return acc
}, [])
return categories
}

Modify the Blog Post page

On the single blog post page, loop through the categories and link them to their respective category pages. Update /app/blog/[slug]/page.js

<div className="flex justify-center space-x-3">
{categories.map((category) => (
<Link
key={category}
href={`/category/${category}`}
className="bg-gray-100 text-gray-500 px-2 py-1 rounded text-xs"
>
{category}
</Link>
))}
</div>

After adding this code block above, this will be the complete code:

import { getPostMetaData, getSinglePost } from "@/lib/articles"
import isEmpty from 'lodash/isEmpty'
import ReactMarkdown from 'react-markdown'
import rehypeRaw from 'rehype-raw'
import rehypeHighlight from 'rehype-highlight';
import rehypeHighlightCodeLines from 'rehype-highlight-code-lines'
import Image from "next/image"
import Link from "next/link"
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import 'highlight.js/styles/tokyo-night-dark.css'; // Replace with your preferred theme
export const generateStaticParams = async () => {
const postMetaData = getPostMetaData()
const paths = postMetaData.map((post) => {
return {
slug: post.slug
}
})
return paths
}
export const generateMetadata = async ({ params }) => {
const { slug } = await params;
const postMetaData = getPostMetaData()
const currentPost = postMetaData.find((post) => post.slug === slug)
if (isEmpty(currentPost)) {
return {
title: 'My Blog',
description: 'My Blog Description'
};
}
return {
title: `${currentPost.title} | My Blog`,
description: currentPost.description,
image: currentPost.image,
keywords: currentPost.category,
date: currentPost.date,
category: currentPost.category
};
};
const BlogPost = async ({ params }) => {
const { slug } = await params
const fileContent = getSinglePost(slug)
const { content, data: meta } = fileContent;
const { title, categories, date, description, image } = meta
return (
<>
<div className="flex items-center justify-between text-sm text-gray-500 py-6">
<Link href="/blog" className="flex space-x-4 items-center">
<ArrowLeftIcon className="w-6 h-6" />
<span>All Posts</span>
</Link>
<div className="space-x-4">
<span>{new Date(date).toLocaleDateString("en-US", {
year: "numeric",
month: "short",
day: "numeric"
})}</span>
</div>
</div>
<div className="flex justify-center space-x-3">
{categories.map((category) => (
<Link
key={category}
href={`/category/${category}`}
className="bg-gray-100 text-gray-500 px-2 py-1 rounded text-xs"
>
{category}
</Link>
))}
</div>
<div className="text-neutral-800 text-center p-6">
<h1 className="font-gloock text-4xl mb-6">{title}</h1>
<p>{description}</p>
</div>
{image && (
<div className="mb-9">
<Image
src={image}
width="600"
height="400"
alt={`Featured image for ${title}`}
className="w-full max-h-[500px] object-cover shadow-md"
/>
</div>
)}
<article className="blogpost prose prose-slate prose-h1:font-gloock prose-h2:font-gloock prose-h1:text-3xl prose-h2:text-[24px] md:prose-h2:text-[27px] prose-headings:tracking-wider prose-headings:text-gray-800 max-w-screen-md pb-12 prose-pre:text-base prose-pre:bg-[#001825] prose-blockquote:bg-slate-200 prose-blockquote:p-3 prose-blockquote:border-l-8 prose-blockquote:border-red-600 break-words">
<ReactMarkdown rehypePlugins={[rehypeRaw, rehypeHighlight, [rehypeHighlightCodeLines, {
showLineNumbers: true,
lineContainerTagName: 'div'
}]]}>
{content}
</ReactMarkdown>
</article>
</>
)
}
export default BlogPost

Create the Category Page

New Page /app/category/[category]/page.js:

import { getPostMetaData, getAllCategories } from "@/lib/articles"
import Card from "@/components/Card"
export const generateStaticParams = async () => {
const categories = getAllCategories();
const paths = categories.map((category) => {
return {
category
}
});
return paths
}
const Category = async ({ params }) => {
const { category } = await params
const posts = getPostMetaData();
const filteredPosts = posts.filter((post) => post.categories.includes(category));
return (
<section>
<header className="font-gloock py-6">
<h1 className="text-4xl text-neutral-800 text-center capitalize">{category} Posts</h1>
</header>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 py-6">
{filteredPosts.map((post) => (
<Card
key={post.id}
slug={post.slug}
title={post.title}
category={post.category}
date={post.date}
description={post.description}
image={post.image}
/>
))}
</div>
</section>
);
}
export default Category

Create the Categories Listing Page

New Page /app/categories/page.js

import { getAllCategories } from "@/lib/articles";
import Link from "next/link";
const Categories = () => {
const categories = getAllCategories();
return (
<section>
<header className="font-gloock py-6 mb-4">
<h1 className="text-4xl text-neutral-800 text-center">Categories</h1>
</header>
<ul className="flex flex-wrap gap-4 justify-center">
{categories.map((category) => (
<Link key={category} href={`/category/${category}`} className="bg-gray-100 text-gray-500 px-2 py-1 rounded">
{category}
</Link>
))}
</ul>
</section>
);
}
export default Categories

By following the steps outlined above, you can seamlessly implement categories for your Next.js markdown blog. This setup allows you to associate multiple categories with a post, create dynamic category pages, and display a category listing for better content organization.