Creating a Blog Webpage using Next.js
Last Updated :
23 Jul, 2025
In this article, we will delve into the process of setting up a blog, with NextJS, a known React framework. The blog will come equipped with features that enable users to compose, view, edit, and remove blog entries. We'll make use of NextJS capabilities to construct a speedy and search-engine-optimized site.
Output Preview: Let us have a look at how the final output will look like.
Final OutputPrerequisites:
Approach to Create a Blog Webpage with NextJS:
- Posts Handling (posts.ts): Fetches posts data from markdown files. Parses metadata using gray-matter. Converts markdown content to HTML using remark.
- Date Formatting (getFormattedDate.ts): Formats date strings using Intl.DateTimeFormat.
- List Item Component (ListItem.tsx): Displays individual post titles and dates. Links to respective post pages.
- Profile Picture Component (MyProfilePic.tsx): Displays a profile picture using Next.js Image component.
- Navbar Component (Navbar.tsx): Navigation bar with site title and links. Utilizes React icons for social media links.
- Layout Component (layout.tsx): Sets up the overall layout including navbar and profile picture. Allows for global styling and structure.
- Post Page (page.tsx): Fetches and displays individual post content. Provides links back to the homepage.
- Homepage (index.tsx): Displays a greeting message and lists posts using the Posts component.
Steps to Create a NeaxtJS App and Installing Module:
Step 1: Create a New NextJS Project Using Command.
npx create-next-app@latest --ts
Step 2: Change the current directory using Command.
cd <<Name_of_project>>
Step 3: Run the Server by following command.
npm run dev
Step 3: Remove all the boilerplate code from the page.tsx file
Step 4: Remove the page.module.css file from the app directory and clear all the code from globals.css file
Step 5: Install Tailwind by following command
npm install -D tailwindcss postcss autoprefixernpx tailwindcss init -p
Step 6: Configure Tailwind by adding the below code to the tailwind.config.js file in content section
"./app/**/*.{js,ts,jsx,tsx,mdx}", "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}",
Project Structure:

Step 7: Create the Markdown Files and add the following code
To start make a main folder named "blogposts" (different, from pages/posts) in your main directory. Within the posts folder generate two files; one called pre-rendering.md and another named ssg-ssr.md. Next paste the provided code into the file.
JavaScript
// Pre-rendering.md
---
title: 'Server-side Rendering'
date: '2024-02-29'
---
Hello: **Static Generation** and **Server-side Rendering**. The difference is in **when** it generates the HTML for a page.
- **Static Generation** is the pre-rendering method that generates the HTML at **build time**. The pre-rendered HTML is then _reused_ on each request.
- **Server-side Rendering** is the pre-rendering method that generates the HTML on **each request**.
Importantly, Next.js lets you **choose** which pre-rendering form to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.
JavaScript
//ssg-ssr.md
---
title: 'Static Generation'
date: '2024-03-01'
---
We recommend using **Static Generation** (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request.
You can use Static Generation for many types of pages, including:
- Marketing pages
- Blog posts
- E-commerce product listings
- Help and documentation
You should ask yourself: "Can I pre-render this page **ahead** of a user's request?" If the answer is yes, then you should choose Static Generation.
On the other hand, Static Generation is **not** a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request.
In that case, you can use **Server-Side Rendering**. It will be slower, but the pre-rendered page will always be up-to-date. Or you can skip pre-rendering and use client-side JavaScript to populate data.
You may have observed that every markdown document includes a metadata segment, with the title and date.
This section is referred to as YAML Front Matter. It can be interpreted using a tool named gray-matter.
Step 8: Install the gray-matter
npm install gray-matter
Step 9: Create a Utility function which will read the file-system
Lets move on to developing a tool that can help us extract information from the file system. This tool will allow us to:
- In each document extract the title, date and file name (to serve as the post URL id).
- List the data on the page organized by date.
Begin by setting up a folder named lib in the main directory. Next within the lib folder establish a document titled posts.ts and getFormattedDate.ts then insert the following code snippet;
Step 10: Write the following code in different files with the file structure. Create a components folder in your app directory and add this four following files:
- Listitem.tsx
- MyProfilePic.txt
- Navbar.tsx
- Posts.tsx
Step 11: Create a sub folder in posts directory called [postid] and add these files following the structure
- not-found.tsx
- page.tsx [this will be in your sub folder]
- layout.tsx
- page.tsx
JavaScript
// posts.ts
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(),
'blogposts')
export 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);
const blogPost: BlogPost = {
id,
title: matterResult.data.title,
date: matterResult.data.date,
}
// Combine the data with the id
return blogPost
});
// Sort posts by date
return allPostsData.sort(
(a, b) => a.date < b.date ? 1 : -1);
}
export async function getPostData(id: string) {
const fullPath = path.join(postsDirectory, `${id}.md`);
const fileContents = fs.readFileSync(fullPath, 'utf8');
// Use gray-matter to parse the post metadata section
const matterResult = matter(fileContents);
const processedContent = await remark()
.use(html)
.process(matterResult.content);
const contentHtml = processedContent.toString();
const blogPostWithHTML: BlogPost & {
contentHtml: string
} = {
id,
title: matterResult.data.title,
date: matterResult.data.date,
contentHtml,
}
// Combine the data with the id
return blogPostWithHTML
}
JavaScript
// getFormattedDate.ts
export default function getFormattedDate(dateString: string): string {
return new Intl.DateTimeFormat('en-US',
{ dateStyle: 'long' }).format(new Date(dateString))
}
JavaScript
// Listitem.tsx
import Link from "next/link"
import getFormattedDate from "@/lib/getFormattedDate"
type Props = {
post: BlogPost
}
export default function ListItem({ post }: Props) {
const { id, title, date } = post
const formattedDate = getFormattedDate(date)
return (
<li className="mt-4 text-2xl dark:text-black/90">
<Link
className="underline hover:text-black/70
dark:hover:text-green"
href={`/posts/${id}`}>{title}</Link>
<br />
<p className="text-sm mt-1">
{formattedDate}
</p>
</li>
)
}
JavaScript
// MyProfilePic.tsx
import Image from "next/image"
export default function MyProfilePic() {
return (
<section className="w-full mx-auto">
<Image
className="border-4 border-black dark:border-green-500
drop-shadow-xl shadow-black rounded-full mx-auto mt-8"
src="/images/icons8-geeksforgeeks-600.png"
width={200}
height={200}
alt="Geek"
priority={true}
/>
</section>
)
}
JavaScript
// Navbar.tsx
import Link from "next/link"
import {
FaYoutube,
FaTwitter,
FaGithub,
FaLaptop
} from "react-icons/fa"
export default function Navbar() {
return (
<nav className="bg-green-600 p-4 sticky
top-0 drop-shadow-xl z-10">
<div className="prose prose-xl
mx-auto flex justify-between
flex-col sm:flex-row">
<h1 className="text-3xl font-bold
text-black grid place-content-center
mb-2 md:mb-0">
<Link href="/" className="text-black/90
no-underline hover:text-white">
GeeksForGeeks Blog
</Link>
</h1>
<div className="flex flex-row justify-center
sm:justify-evenly align-middle
gap-4 text-black text-4xl lg:text-5xl">
</div>
</div>
</nav>
)
}
JavaScript
// Posts.tsx
import { getSortedPostsData } from "@/lib/posts"
import ListItem from "./ListItem"
export default function Posts() {
const posts = getSortedPostsData()
return (
<section className="mt-6 mx-auto max-w-2xl">
<h2 className="text-4xl font-bold
dark:text-black/90">
Blog
</h2>
<ul className="w-full">
{posts.map(post => (
<ListItem key={post.id} post={post} />
))}
</ul>
</section>
)
}
JavaScript
import Link from "next/link"
import getFormattedDate from "@/lib/getFormattedDate"
type Props = {
post: BlogPost
}
export default function ListItem({ post }: Props) {
const { id, title, date } = post
const formattedDate = getFormattedDate(date)
return (
<li className="mt-4 text-2xl dark:text-black/90">
<Link className="underline hover:text-black/70
dark:hover:text-green" href={`/posts/${id}`}>
{title}
</Link>
<br />
<p className="text-sm mt-1">{formattedDate}</p>
</li>
)
}
JavaScript
// layout.tsx
import './globals.css'
import Navbar from './components/Navbar'
import MyProfilePic from './components/MyProfilePic'
export const metadata = {
title: "Geeks Blog",
description: 'Created by Geek Blogger',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body className="dark:bg-white-800">
<Navbar />
<MyProfilePic />
{children}
</body>
</html>
)
}
JavaScript
// not-found.tsx
export default function NotFound() {
return (
<h1>The requested post does not exist.</h1>
)
}
JavaScript
// page.tsx ([postid])
import getFormattedDate from "@/lib/getFormattedDate"
import {
getSortedPostsData,
getPostData
} from "@/lib/posts"
import { notFound } from "next/navigation"
import Link from "next/link"
export function generateStaticParams() {
const posts = getSortedPostsData()
return posts.map((post) => ({
postId: post.id
}))
}
export function generateMetadata({ params }:
{ params: { postId: string } }) {
const posts = getSortedPostsData()
const { postId } = params
const post = posts.find(post => post.id === postId)
if (!post) {
return {
title: 'Post Not Found'
}
}
return {
title: post.title,
}
}
export default async function Post({ params }:
{ params: { postId: string } }) {
const posts = getSortedPostsData()
const { postId } = params
if (!posts.find(post => post.id === postId)) notFound()
const { title, date, contentHtml } = await getPostData(postId)
const pubDate = getFormattedDate(date)
return (
<main className="px-6 prose prose-xl prose-green mx-auto">
<h1 className="text-3xl mt-4 mb-0">{title}</h1>
<p className="mt-0">
{pubDate}
</p>
<article>
<section dangerouslySetInnerHTML={{
__html: contentHtml
}} />
<p>
<Link href="/">← Back to home</Link>
</p>
</article>
</main>
)
}
JavaScript
// page.tsx
import Posts from "./components/Posts"
export default function Home() {
return (
<main className="px-6 mx-auto">
<p className="mt-12 mb-12 text-3xl
text-center dark:text-black">
Hello Geeks
<span className="whitespace-nowrap">
</span>
</p>
<Posts />
</main>
)
}
Run the below command to start the server
npm run dev
Output:
Final Output
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability. "Hello, World!" Program in ReactJavaScriptimport React from 'react'; function App() {
6 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides DOM-specific methods to interact with and manipulate the Document Object Model (DOM), enabling efficient rendering and management of web page elements. ReactDOM is used for: Rendering Components: Displays React components in the DOM.DOM Manipulation: Al
2 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsIn lists, React makes it easier to render multiple elements dynamically from arrays or objects, ensuring efficient and reusable code. Since nearly 85% of React projects involve displaying data collectionsâlike user profiles, product catalogs, or tasksâunderstanding how to work with lists.To render a
4 min read
React FormsIn React, forms are used to take input from users, like text, numbers, or selections. They work just like HTML forms but are often controlled by React state so you can easily track and update the input values.Example:JavaScriptimport React, { useState } from 'react'; function MyForm() { const [name,
4 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. When rendering a list, you need to assign a unique key prop to each element in th
4 min read
Components in React
React ComponentsIn React, components are reusable, independent code blocks (A function or a class) that define the structure and behavior of the UI. They accept inputs (props or properties) and return elements that describe what should appear on the screen.Key Concepts of React Components:Each component handles its
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.Example:JavaScriptimport
4 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
3 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem.Type Safety: When the wrong data type is passed in the component, prototypes help find the issues.Better Debugging: During development, t
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects