Next.js is a powerful framework for building server-side rendering (SSR) and static web applications with React. One of the standout features of Next.js is its ability to generate static sites, which can offer improved performance and SEO benefits. In this article, we will explore how to build a simple static blog using Next.js. We’ll cover the setup, creating pages, fetching data, and deploying the static site.
Prerequisites
To follow along with this tutorial, you should have:
- Basic knowledge of React.
- Node.js installed on your machine.
- A text editor or IDE like VSCode.
Setting Up a Next.js Project
First, let's create a new Next.js project. Open your terminal and run the following command:
npx create-next-app my-static-blog
cd my-static-blog
This command will set up a new Next.js project in the my-static-blog directory.
Creating the Blog Post Pages
Next.js uses a file-based routing system. Each file in the pages directory corresponds to a route in the application. We’ll create a posts directory inside the pages directory to hold our blog post files.
mkdir pages/posts
Let's create a sample blog post. Create a file named first-post.js inside the pages/posts directory with the following content:
// pages/posts/first-post.js
import Link from 'next/link';
export default function FirstPost() {
return (
<div>
<h1>First Post</h1>
<p>This is the content of the first post.</p>
<Link href="/">
<a>Back to Home</a>
</Link>
</div>
);
}
Adding Dynamic Routes
For a blog, we often need dynamic routes to handle multiple posts. Next.js provides a powerful way to create dynamic routes using file names enclosed in square brackets. Let’s create a dynamic route for our blog posts.
Create a file named [id].js inside the pages/posts directory:
// pages/posts/[id].js
import { useRouter } from 'next/router';
import Link from 'next/link';
export default function Post() {
const router = useRouter();
const { id } = router.query;
return (
<div>
<h1>{id.replace(/-/g, ' ')}</h1>
<p>This is the content of the post.</p>
<Link href="/">
<a>Back to Home</a>
</Link>
</div>
);
}
Fetching Blog Post Data
To fetch and display the actual content of our blog posts, we can use getStaticProps and getStaticPaths. These functions allow us to fetch data at build time and generate static pages for each blog post.
Create a new directory named posts at the root of your project to store our blog post data:
mkdir posts
Create a file named first-post.md inside the posts directory with the following content:
---
title: "First Post"
date: "2024-06-20"
---
This is the content of the first post.
Update the [id].js file to fetch and display the content of the blog post:
// pages/posts/[id].js
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { useRouter } from 'next/router';
import Link from 'next/link';
const postsDirectory = path.join(process.cwd(), 'posts');
export async function getStaticPaths() {
const filenames = fs.readdirSync(postsDirectory);
const paths = filenames.map((filename) => ({
params: { id: filename.replace(/\.md$/, '') },
}));
return {
paths,
fallback: false,
};
}
export async function getStaticProps({ params }) {
const fullPath = path.join(postsDirectory, `${params.id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
const matterResult = matter(fileContents);
return {
props: {
postData: {
id: params.id,
...matterResult.data,
content: matterResult.content,
},
},
};
}
export default function Post({ postData }) {
return (
<div>
<h1>{postData.title}</h1>
<p>{postData.date}</p>
<div>{postData.content}</div>
<Link href="/">
<a>Back to Home</a>
</Link>
</div>
);
}
Deploying the Static Site
Next.js makes it easy to deploy static sites. First, build the static files by running:
npm run build
npm run export
This will generate a out directory containing the static files for your site. You can then deploy these files to any static site hosting service, such as Vercel, Netlify, or GitHub Pages.
Conclusion
In this tutorial, we've built a simple static blog using Next.js. We covered setting up a Next.js project, creating pages, adding dynamic routes, fetching blog post data, and deploying the static site. Next.js is a versatile framework that simplifies the process of building high-performance web applications.
For more information on Next.js, check out the official documentation.
Happy coding!
Top comments (0)