Skip to main content
Seafold
Loading
All articles

How to Build a Blog with Next.js and MDX

Using Next.js to build a blog is very easy!

Nelson Lai
Loading ViewsLoading Comments

Preface

The packages to be used:

The repository for this tutorial:

https://github.com/nelsonlaidev/nextjs-mdx-blog

Demo

Online demo

How to Create a Blog

First, we create the Next.js project with the following command:

Terminal

Next, create the following files:

  • components/layout.jsx - Wrap all components in a container (optional, just the style)
  • data/blog/*.mdx - Blog Articles
  • lib/format-date.js - Format the date as MM DD, YYYY
  • pages/blog/[slug].jsx - article page, using dynamic routes

Tree view

components
layout.jsx
data
blog
markdown.mdx
nextjs.mdx
react.mdx
lib
format-date.js
mdx.js
pages
blog
[slug].jsx

How to Handle Markdown Files

First, define root as the project root directory. The process.cwd() method returns the current working directory of the Node.js process.

lib/mdx.js

Next, define POSTS_PATH as the directory where the article files are stored.

lib/mdx.js

Then use fs to read the contents of that directory, that is, all the file names under data/blog.

lib/mdx.js

Then write a function to remove the file extension, which will be used later.

lib/mdx.js

The next step is to get the article content by slug.

lib/mdx.js

Then you can get all the articles to be displayed in the home page.

lib/mdx.js

Formatting Dates

lib/format-date.js

Home Page

pages/index.jsx

Article Page

pages/blog/[slug].jsx

This way, a simple blog is finished.

View on GitHub

Thanks for reading.
Every little discovery leads to another.

0 / 3

Comments

Good ideas don’t end at the last line. What’s on your mind?

Loading
Loading comments·Loading replies
Loading