Adding categories to Next.js Markdown blog

By Priyash Patil | Updated: Oct 21, 2023 10AM IST

After following the learn Next.js tutorial, I have code similar to this GitHub Revision. This post is about adding a categories feature for my blog.

Problem statement

If you run the application shared on this GitHub Revision you'll see no blog categories. One of the well-known ways to organize blog content is by categorizing each blog. So, the following is the list of requirements I came up with for adding the categories feature to my blog.

Requirements

Solution

This is a markdown-based blog using Next.js dynamic routing with a Markdown parser to generate static blog content.

Tagging blog posts with categories

In Markdown, one of the well-known ways to add metadata is by adding front matter. So, I'll be using the front matter to tag a post with categories.

Parsing categories into Next.js props

For parsing front matter we are already using the package gray-matter from Jon Schlinkert. This package gives us the front matter where we are going to add categories references.

Finally, we use Next.js dynamic routing and SSG methods getStaticPaths and getStaticProps on a category page.

Source code

The final source code is on this GitHub Revision. Do note that this source repository is not my actual website. I'll be maintaining a separate source code repository for this blog series.

Conclusion

The categories feature works as expected. However, some improvements can be made. For example, a category link for a category My Blog would have a URL path like https://example.com/categories/my%20blog. It can be improved, but It will be out of the scope of this blog. So, stay tuned for the upcoming blog's pretty URLs.