
How to Build a Blog with Next.js
Learn How to Build a Blog with Next.js step-by-step. Create a fast, SEO-friendly, and dynamic blog using modern features like SSR, routing, and API integration.
Steps to create a Blog with Next.js
1. What is Next.js?
The robust React framework Next.js comes with built-in features including server-side rendering, the ability to create static websites, and API routes. It is ideal for creating blogs that are effective with little setup.
Next.js is a robust open-source React framework created by Vercel that makes it simple for developers to create cutting-edge, highly efficient online apps. With features like client-side rendering (CSR), server-side rendering (SSR), static site generation (SSG), API routes, and automatic code splitting, it expands on React's capabilities and is perfect for enterprise dashboards, blogs, and e-commerce sites that require high performance.
Essential Qualities:
Using Hybrid Rendering
The rendering strategies supported by Next.js are as follows:
Static Generation (SSG):
For quick performance and SEO, pages are pre-rendered at build time and formatted as static HTML.
When it comes to dynamic material that changes often, Server-Side Rendering (SSR) is helpful because it renders pages on the server at the moment of request.
Client-side rendering, or CSR, allows for the rendering of interactive components or pages on the client following initial load.
File-Based Routing The routing system used by Next.js is based on files. Route setup is no longer necessary because each file within the pages or directory gets a route automatically.
Routes via APIs
Your Next.js application's pages/api subdirectory is where you can construct backend APIs. Form submissions, authentication, and retrieving external data are all excellent uses for these serverless operations, which operate on demand.
Integrated Support for Sass and CSS Next. Sass, global styles, and CSS Modules are all supported by JavaScript by default. Additionally, Tailwind CSS and other utility-first frameworks are easy to integrate with.
Optimization of Images
The integrated component enhances efficiency and load times by automatically optimizing pictures for various screen sizes and resolutions.
Optimization of Performance
By ensuring that customers only download the essential code, Next.js reduces initial load times through smart bundling, slow loading, and intelligent code splitting.
Optimized for search engines
Compared to conventional single-page apps, Next.js apps are more SEO-friendly due to their capacity to render pages on the server or at build time.
Use Cases:
- · Blogs and content websites
- · E-commerce stores
- · SaaS dashboards
- · Documentation sites
- · Portfolios
Important Elements of a Blog:
- - Routing based on files
- - Static Generation (SSG)
- - Integration of Markdown
- - API routes (CMS optional)
- -SEO and image optimization
Explore Other Demanding Courses
No courses available for the selected domain.
1. Next.js Project Setup
Requirements:
- - Node.js
- - React Basic Understanding
- 1. Initialized the Project with the following command
> npx create-next-app@latest nextjs-myblog
After executing this command, add the project to the project directory with,
> cd nextjs-myblog
- 2. Install Dependencies
npm install gray-matter remark remark-html
note:
gray-matter : for Parses frontmatter from markdown files
remark : for processes markdown
remark-html : for converting markdown to html
2. Creating Pages and Routes
The /pages directory contains the file-based routing mechanism used by Next.js.
Project Structure,
pages/
index.js - Home page
blog/ - Dynamic route for every blog post
[slug].js
posts/ - Directory to store markdown files
first-post.md
second-post.md
third-post.md
3. Writing Blog posts using a markdown file
First create a folder “posts” in main project folder
mkdir posts
then create markdown file in posts folder with content like:
posts/first-post.md
posts/second-post.md
posts/third-post.md
4. Loading Markdown to HTML
Develop a helper function for loading and parsing Markdown.
lib/posts.js
import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'
import { remark } from 'remark'
import html from ‘remark-html’
const postsMyDirectory = path.join(process.cwd(), 'posts')
export function getSortedMyPostsData() {
const fileNames = fs.readdirSync(postsMyDirectory)
const allPostsData = fileNames.map((fileName) => {
const id = fileName.replace(/\.md$/, '')
const fullPath = path.join(postsMyDirectory, 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(postsMyDirectory, `${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
}
}
pages/index.js
import Head from 'next/head'
import Link from 'next/link'
import { getSortedMyPostsData } from ‘../lib/posts’
export async function getMyStaticProps() {
const allPostsData = getSortedMyPostsData()
return {
props: {
allPostsData
}
}
}
export default function Home({ allPostsData }) {
return (
<>
<Head>
<title>My Blog</title>
</Head>
<main>
<h1>My Blog</h1>
<ul>
{allPostsData.map(({ id, title, date }) => (
<li key={id}>
<Link href={`/blog/${id}`}>{title}</Link>
<br />
<small>{date}</small>
</li>
))}
</ul>
</main>
</>
)
}
5. Dynamic routing for Blog post
pages/blog/[slug].js
import { getAllPostIds, getPostData } from '../../lib/posts'
import Head from ‘next/head’
export async function getStaticPaths() {
const paths = getSortedMyPostsData().map(post => ({
params: { slug: post.id }
}))
return {
paths,
fallback: false
}
}
export async function getStaticProps({ params }) {
const postData = await getPostData(params.slug)
return {
props: {
postData
}
}
}
export default function Post({ postData }) {
return (
<>
<Head>
<title>{postData.title}</title>
</Head>
<article>
<h1>{postData.title}</h1>
<div><small>{postData.date} | {postData.author}</small></div>
<div dangerouslySetInnerHTML={{ __html: postData.contentHtml }} />
</article>
</>
)
}
Styling with CSS Modules
h1 {
font-size: 2.5rem;
color: #333;
}
ul {
list-style: none;
padding: 0;
}
li {
margin-bottom: 1rem;
}
6. Optimization
Using <Head> from next/head:
Add dynamic <title>, <meta name="description">, and Open Graph tags for each blog post.
Example in [slug].js:
<Head>
<title>{postData.title}</title>
<meta name="description" content={`Read this blog: ${postData.title}`} />
<meta property="og:title" content={postData.title} />
</Head>
Add to index.js
import styles from '../styles/Home.module.css'
...
<h1 className={styles.title}>My Blog</h1>
7. Deploying the blog
Vercel is the developer of Next.js, and deployment is easy.
Steps:
- 1. Upload your work to GitHub.
- 2. Sign in by visiting https://vercel.com.
- 3. Select "New Project" → Bring in your GitHub repository.
- 4. Next.js should be the framework.
- 5. Press “Deploy.”
Do visit our channel to learn more: SevenMentor