Building a Blog with Next.js and Markdown
Tags: webdev, beginners, programming, javascript
Published: 2024-02-21 12:23:32

Creating a blog with Next.js and Markdown is a fantastic way to leverage modern web technologies for efficient, scalable content management. In this LinkedIn article, we'll explore how to set up a simple blog using Next.js, a popular React framework, and Markdown, a lightweight markup language for creating formatted text. This approach allows developers to enjoy the benefits of a React-based frontend while easily managing and writing blog content in Markdown.

Introduction to Next.js and Markdown
Next.js is a React framework that enables functionalities such as server-side rendering and generating static websites, making it an excellent choice for building fast and SEO-friendly blogs. Markdown, on the other hand, allows writers to format their text without the need for complex HTML, making content creation straightforward and manageable.

Setting Up Your Next.js Project
First, let's create a new Next.js project. If you haven't installed Node.js, do that first. Then, open your terminal and run:

```
npx create-next-app my-blog
cd my-blog
```
This command creates a new Next.js application in the my-blog directory.

Adding Markdown Support
To handle Markdown files, we'll use gray-matter and remark libraries. gray-matter parses metadata in Markdown files, and remark is used for converting Markdown into HTML.

Install these dependencies:

```
npm install gray-matter remark remark-html
```

Creating the Blog Structure
Inside your Next.js project, create a new directory called posts at the root. This directory will store your Markdown blog posts.

Writing Your First Blog Post
Create a new file in the posts directory, for example, my-first-post.md. At the top of the file, add some front matter for metadata, followed by your Markdown content:

```
---
title: "My First Post"
date: "2024-02-21"
---

Welcome to my first blog post using Next.js and Markdown!

```
Parsing Markdown Files
Create a new file called posts.js in the lib directory (you might need to create the lib directory as well). This file will contain the logic to parse Markdown files and convert them into a format that our Next.js application can use.

```
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { remark } from 'remark';
import html from 'remark-html';

const postsDirectory = path.join(process.cwd(), 'posts');

export async function getSortedPostsData() {
  // Get file names under /posts
  const fileNames = fs.readdirSync(postsDirectory);
  const allPostsData = fileNames.map(fileName => {
    // Remove ".md" from file name to get id
    const id = fileName.replace(/\.md$/, '');

    // Read markdown file as string
    const fullPath = path.join(postsDirectory, fileName);
    const fileContents = fs.readFileSync(fullPath, 'utf8');

    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents);

    // Combine the data with the id
    return {
      id,
      ...matterResult.data
    };
  });
  // Sort posts by date
  return allPostsData.sort(({ date: a }, { date: b }) => {
    if (a < b) {
      return 1;
    } else if (a > b) {
      return -1;
    } else {
      return 0;
    }
  });
}

```
Displaying Posts
Now, modify the index.js file in the pages directory to display your blog posts. Import getSortedPostsData from the lib/posts.js file and use getStaticProps to fetch posts data:

```
import { getSortedPostsData } from '../lib/posts';

export async function getStaticProps() {
  const allPostsData = getSortedPostsData();
  return {
    props: {
      allPostsData
    }
  };
}

export default function Home({ allPostsData }) {
  return (
    <ul>
      {allPostsData.map(({ id, date, title }) => (
        <li key={id}>
          {title}
          <br />
          {id}
          <br />
          {date}
        </li>
      ))}
    </ul>
  );
}
```
Conclusion
You've now set up a basic blog using Next.js and Markdown. This setup allows you to write posts in Markdown, automatically parse them into HTML, and render them using Next.js, creating a fast, SEO-friendly, and easily manageable blog. As you become more familiar with Next.js and Markdown, you can explore more advanced features, such as dynamic routing for blog posts, customizing Markdown rendering, and adding a content management system (CMS) for an even more powerful blogging platform.

By leveraging the simplicity of Markdown for content creation and the robustness of Next.js for web development, you can create an efficient and scalable blogging platform that suits your needs.

---

Thank you for reading my article! For more updates and useful information, feel free to connect with me on LinkedIn and follow me on Twitter. I look forward to engaging with more like-minded professionals and sharing valuable insights.