How to build a blog with Next.js and MDX
Using Next.js to build a blog is very easy!

Aayush Bharti
Preface
The packages to be used:
- next Next.js framework
- next-mdx-remote handling and loading mdx content
- gray-matter parse the front matter in markdown
How to create a blog
First, we create the Next.js project with the following command:
Next, create the following file structure:
components/layout.jsx
- Wrap all components in a container (optional, just the style)data/blog/*.mdx
- Blog Articleslib/format-date.js
- Format the date asMM DD, YYYY
pages/blog/[slug].jsx
- Article page, using dynamic routes
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.
Next, create the POSTS_PATH
constant for the path where the article files are
stored:
Then use fs
to read the contents of that directory (all the file names under
data/blog
):
Now, write a function to remove the file extension (useful later):
The next step is to get the article content by slug:
Get all blog posts
You can get all the articles to be displayed on the homepage: