Sitemap

Using Markdown with Next.js

4 min readSep 3, 2024

Creating a blog is an exciting project for anyone looking to share their thoughts, expertise, or experiences with the world. Using Markdown and Next.js can make the process both straightforward and powerful. Here’s a comprehensive guide on how to create a blog using these technologies.

Introduction to Markdown and Next.js

Markdown is a lightweight markup language that you can use to add formatting elements to plaintext text documents. It’s often used for writing content because of its simplicity and readability. With Markdown, you can easily create headings, lists, links, images, and more without needing to delve into complex HTML.

Next.js is a popular React framework that provides server-side rendering, static site generation, and a rich ecosystem of tools and plugins. It’s ideal for building fast, SEO-friendly websites, including blogs. Combining Next.js with Markdown allows you to create a blog that’s not only fast and easy to manage but also scalable and customizable.

Setting Up Your Next.js Blog

1. Initialize a New Next.js Project
First, you’ll need to set up a new Next.js project. If you haven’t already installed Node.js, do so, and then open your terminal and run the following command:

```bash
npx create-next-app@latest my-blog
```

Replace `my-blog` with your preferred project name. This command will create a new directory with all the necessary files and dependencies to start a Next.js application.

2. **Install Dependencies**
Once your project is set up, navigate to your project directory and install the necessary packages for handling Markdown files. You’ll need `gray-matter` for parsing front matter (metadata) in Markdown files and `remark` with `remark-html` for converting Markdown to HTML:

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

3. Create Your Blog Structure
Create a directory for your blog posts. This directory will store all your Markdown files:

```bash
mkdir posts
```

Inside this `posts` folder, create your first Markdown file, `hello-world.md`:

```markdown
— -
title: “My Blog Post”
date: “2024–09–03”
— -

Welcome to my blog! This is my first post written in Markdown.
```

The content between the ` — -` lines is the front matter, where you can define metadata like the title and date of your post.

4. Fetch and Parse Markdown Files
In your Next.js project, create a utility function to read and parse these Markdown files. This function will extract the metadata and convert the content to HTML.

Create a file named `lib/posts.js`:

```javascript
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 function getSortedPostsData() {
const fileNames = fs.readdirSync(postsDirectory);
const allPostsData = fileNames.map((fileName) => {
const id = fileName.replace(/\.md$/, ‘’);
const fullPath = path.join(postsDirectory, fileName);
const fileContents = fs.readFileSync(fullPath, ‘utf8’);
const matterResult = matter(fileContents);

return {
id,
…matterResult.data,
};
});

return allPostsData.sort((a, b) => (a.date < b.date ? 1 : -1));
}

export async function getPostData(id) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, ‘utf8’);
const matterResult = matter(fileContents);
const processedContent = await remark()
.use(html)
.process(matterResult.content);
const contentHtml = processedContent.toString();

return {
id,
contentHtml,
…matterResult.data,
};
}
```

5. Create Dynamic Pages for Each Post
Next.js allows you to create dynamic routes for each post based on the Markdown file names. Inside the `pages` directory, create a new folder called `posts`, and then add a file named `[id].js`:

```javascript
import { getAllPostIds, getPostData } from ‘../../lib/posts’;

export async function getStaticPaths() {
const paths = getAllPostIds();
return {
paths,
fallback: false,
};
}

export async function getStaticProps({ params }) {
const postData = await getPostData(params.id);
return {
props: {
postData,
},
};
}

export default function Post({ postData }) {
return (
<article>
<h1>{postData.title}</h1>
<div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />
</article>
);
}
```

This file handles the dynamic routing for each blog post. The `getStaticPaths` function generates paths for all your blog posts, and `getStaticProps` fetches the content of the post based on the `id` (which corresponds to the Markdown file name).

6. List All Blog Posts on the Homepage
Finally, you’ll want to display a list of all your blog posts on the homepage. In `pages/index.js`, update your code to fetch and render the list of posts:

```javascript
import { getSortedPostsData } from ‘../lib/posts’;

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

export default function Home({ allPostsData }) {
return (
<section>
<h1>My Blog</h1>
<ul>
{allPostsData.map(({ id, title, date }) => (
<li key={id}>
<a href={`/posts/${id}`}>
{title}
</a>
<br />
<small>{date}</small>
</li>
))}
</ul>
</section>
);
}
```

Customizing and Deploying Your Blog

Once your blog is up and running, you can customize its appearance and functionality. You might want to explore adding a global CSS file, implementing dark mode, or setting up a comment system.

When you’re ready to go live, you can deploy your Next.js blog to platforms like Vercel or Netlify with just a few clicks.

Conclusion

Creating a blog with Markdown and Next.js is a fantastic way to get started with modern web development. It offers a perfect blend of simplicity and power, allowing you to focus on writing content while enjoying the flexibility of a robust React framework. Whether you’re a seasoned developer or a beginner, this setup is an excellent foundation for a fast, scalable, and maintainable blog.

--

--

Lindsey Howard
Lindsey Howard

Written by Lindsey Howard

Frontend Web Developer | based in Fort Walton Beach, FL | dog sitter | southern raised | 🐚 beach = happiness ❥

No responses yet