Skip to main content

Command Palette

Search for a command to run...

How to build a blog with Next.js and MDX

Written by
Avatar of Nelson Lai
Nelson Lai
Published on
--
Views
--
Comments
--
How to build a blog with Next.js and MDX

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 file:

  • components/layout.jsx - Wrap all components in a container (optional, just the style)
  • date/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 const root - the root directory, and the process.cwd() method returns the current working directory of the Node.js process.

JavaScript
lib/mdx.js

Another variable POSTS_PATH for the path where the article files are stored.

JavaScript
lib/mdx.js

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

JavaScript
lib/mdx.js

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

JavaScript
lib/mdx.js

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

JavaScript
lib/mdx.js

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

JavaScript
lib/mdx.js

Formatting Date

JavaScript
lib/format-date.js

Home page

React
pages/index.jsx

Article Page

React
pages/[slug].jsx

This way, a simple blog is finished.

Edit on GitHub
Last updated: --