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.
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.
- A blog post should show a list of categories attached to the post.
- There should be a default category
Uncategorizedif there aren't any categories attached to the post.
- Each category should have its own page to show the list of blogs that are attached to the selected category.
- Home Page (index) and Single Post Page content should show links to each attached category page.
- Keep category link paths lowercase. (Optional)
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
getStaticProps on a category page.
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.
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.