Building a Simple Blog with Next.js
Learn how to create a basic blog using Next.js and Markdown files.
Introduction
To get started with building a simple blog using Next.js, you'll need to have Node.js installed on your machine. First, create a new Next.js project using the command npx create-next-app my-blog.
Step 1: Create a New Page
Create a new file called pages/index.js and add the following code:
import Head from 'next/head';
function Home() {
return (
<div>
<Head>
<title>My Blog</title>
</Head>
<h1>Welcome to my blog!</h1>
</div>
);
}
export default Home;
Step 2: Add Markdown Support
To add Markdown support, install the remark and remark-html packages using the command npm install remark remark-html. Then, create a new file called components/Markdown.js and add the following code:
import remark from 'remark';
import html from 'remark-html';
function Markdown({ children }) {
const markdown = remark().use(html);
const content = markdown.processSync(children);
return <div dangerouslySetInnerHTML={{ __html: content.contents }} />;
}
export default Markdown;
Step 3: Create a Blog Post
Create a new file called posts/my-first-post.md and add the following Markdown content:
# My First Post
This is my first blog post!
Then, create a new file called pages/posts/[slug].js and add the following code:
import fs from 'fs';
import path from 'path';
import Markdown from '../components/Markdown';
function Post({ content }) {
return (
<div>
<Markdown>{content}</Markdown>
</div>
);
}
export async function getStaticProps({ params }) {
const markdown = fs.readFileSync(path.join('posts', `${params.slug}.md`), 'utf8');
return { props: { content: markdown } };
}
export async function getStaticPaths() {
const files = fs.readdirSync('posts');
return {
paths: files.map((file) => ({ params: { slug: file.replace('.md', ) } })),
: ,
};
}
;
Ready for more? These paid resources pick up where this lesson leaves off.
Project-based nextjs video courses — the perfect paid next step after these free lessons.
Browse on Udemy →Hand-picked nextjs books to master the fundamentals offline.
See on Amazon →Some links on this page are affiliate links: we may earn a commission at no extra cost to you. We only recommend tools we believe are genuinely useful.