Creating a simple blog architecture
The blog posts in our example will be stored as local markdown files in our application's directory (not fetched from an external data source), so we'll need to read the data from the file system.
In this section, we'll go through the steps of creating a blog that reads markdown data from the file system.
Creating the markdown files
First, create a new top-level directory called posts
(this is not the same as pages/posts
) in your root folder. Inside posts
, create two files: pre-rendering.md
and ssg-ssr.md
.
Now, copy the following code to posts/pre-rendering.md
:
Then, copy the following code to posts/ssg-ssr.md
:
You might have noticed that each markdown file has a metadata section at the top containing
title
anddate
. This is called YAML Front Matter, which can be parsed using a library called gray-matter.
Installing gray-matter
First, install gray-matter which lets us parse the metadata in each markdown file.
Creating the utility function to read the file system
Next, we’ll create a utility function for parsing data from the file system. With this utility function, we’d like to:
- Parse each markdown file and get
title
,date
, and file name (which will be used asid
for the post URL). - List the data on the index page, sorted by date.
Create a top-level directory called lib
in the root directory. Then, inside lib
, create a file called posts.js
, and copy and paste this code:
Note:
You don't need to understand what the code above is doing in order to learn Next.js, the function is to make the blog example functional. But if you'd like to learn more:
fs
is a Node.js module that lets you read files from the file system.path
is a Node.js module that lets you manipulate file paths.matter
is a library that lets you parse the metadata in each markdown file.- In Next.js, the
lib
folder does not have an assigned name like thepages
folder, so you can name it anything. It's usually convention to uselib
orutils
.
Fetching the blog data
Now that the blog data is parsed, we need to add it to our index page (pages/index.js
). We can do this with a Next.js data fetching method called getStaticProps()
. In the next section, we'll learn how to implement getStaticProps()
.
Let’s do it on the next page!