All Posts
Dec 25, 2024

Create a Markdown Blog using NextJs step by step

Learn how to set up a simple Next.js blog with Tailwind CSS, custom components, dynamic fonts, and markdown integration.

Featured image for Create a Markdown Blog using NextJs step by step

Project Setup

In this tutorial, we'll build a simple blog using Next.js. We'll cover everything from setting up the project to creating components, integrating markdown files, and displaying posts dynamically.


1. Install Next.js:

Run the following command to create a new Next.js app:

npx create-next-app@latest simple-blog

This installs Next.js (v15.1.2) which comes with react 19, and reactDOM 19.

2. Create Pages

By default, the home page is located in app/page.js. Let's add two more pages: Blog and Categories.

  • Create two folders inside the app directory: blog and categories.
  • Inside each folder, create a page.js file with some placeholder content.

3. Add Icons

Install Heroicons for adding icons to your project:

npm install @heroicons/react

4. Organize Your Project

Create the following folders at the root level:

  • components - to add all the components.
  • articles - to add our blog posts in markdown format
  • lib - to add helper functions

5. Add Components

Add components Navbar, NavLinks, and Footer in the components folder.

Navbar Component

"use client";
import { useState, useEffect, useCallback } from "react";
import Link from "next/link";
import NavLinks from "./NavLinks";
import { Bars3BottomRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
const Navbar = ({ navLinks = [] }) => {
const [isOpen, setIsOpen] = useState(false);
useEffect(() => {
document.body.style.overflow = isOpen ? "hidden" : "auto";
return () => {
document.body.style.overflow = "auto";
};
}, [isOpen])
const closeMenu = () => setIsOpen(false);
const toggleMenu = useCallback(() => setIsOpen(prev => !prev), []);
return (
<header className="shadow-md py-3 sticky top-0 backdrop-blur">
<nav className="md:max-w-7xl md:mx-auto flex items-center justify-between px-5">
<Link href='/' className="font-gloock text-2xl text-gray-800">
My Blog
</Link>
<div className="hidden md:block space-x-5">
<NavLinks navlinks={navLinks} />
</div>
<div className="md:hidden">
<button
onClick={toggleMenu}
aria-label={isOpen ? "Close menu" : "Open menu"}
aria-expanded={isOpen}
>
{isOpen ? (
<XMarkIcon className="w-7 h-7" />
) : (
<Bars3BottomRightIcon className="w-7 h-7" />
)}
</button>
{isOpen && (
<div className="flex flex-col space-y-3 fixed top-0 right-0 w-full h-svh bg-gray-100 px-10 py-5">
<button onClick={closeMenu} className="w-full flex justify-end mb-5">
<XMarkIcon className="w-7 h-7" />
</button>
<NavLinks navlinks={navLinks} onClick={closeMenu} />
</div>
)}
</div>
</nav>
</header>
)
};
export default Navbar;

NavLinks Component

This Navbar component (Header) needs a NavLinks component which will be added in the same components folder.

import Link from 'next/link'
const NavLinks = ({ navlinks = [], onClick = () => { } }) => {
if (navlinks.length === 0) {
return null
}
return (
<>
{
navlinks.map((link) => {
return (
<Link key={link.href} href={link.href} onClick={onClick}>
{link.label}
</Link>
)
})
}
</>
)
}
export default NavLinks

Footer Component

Add a Footer component in the same components folder for the Layout.

"use client";
import NavLinks from "./NavLinks"
const currentYear = new Date().getFullYear();
const Footer = ({ navLinks }) => {
return (
<footer className="bg-slate-800">
<div className="mx-auto max-w-5xl px-4 py-16 sm:px-6 lg:px-8">
<p className="mx-auto max-w-md text-center leading-relaxed text-gray-500">
&copy; {currentYear} My Blog. All rights reserved.
</p>
<div className="flex justify-center space-x-5 text-gray-500 border-t border-gray-700 pt-6 mt-6">
<NavLinks navlinks={navLinks} />
</div>
</div>
</footer>
)
}
export default Footer

6. Layout Integration

Edit the app/layout.js file include the Navbar and Footer.

import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
const navLinks = [
{ href: "/", label: "Home" },
{ href: "/blog", label: "Blog" },
{ href: "/categories", label: "Categories" },
];
export default function RootLayout({ children }) {
return (
<html lang="en">
<body
className={`${poppins.variable} ${gloock.variable} antialiased`}
>
<Navbar navLinks={navLinks} />
<main className="md:max-w-7xl md:mx-auto px-5 py-6">
{children}
</main>
<Footer navLinks={navLinks} />
</body>
</html>
);
}

7. Fonts and Styling

Add Google Fonts

Import Poppins and Gloock fonts in app/layout.js. Create font variables, and pass them as classNames to body as shown below:

import { Poppins, Gloock } from "next/font/google";
import "./globals.css";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
const poppins = Poppins({
variable: "--font-poppins",
subsets: ["latin"],
weight: ["400", "600", "700"],
});
const gloock = Gloock({
variable: "--font-gloock",
subsets: ["latin"],
weight: ["400"],
});
export const metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
const navLinks = [
{ href: "/", label: "Home" },
{ href: "/blog", label: "Blog" },
{ href: "/categories", label: "Categories" },
];
export default function RootLayout({ children }) {
return (
<html lang="en">
<body
className={`${poppins.variable} ${gloock.variable} antialiased`}
>
<Navbar navLinks={navLinks} />
<main className="md:max-w-7xl md:mx-auto px-5 py-6">
{children}
</main>
<Footer navLinks={navLinks} />
</body>
</html>
);
}

Extend Tailwind Config

Update tailwind.config.mjs to include the new fonts.

/** @type {import('tailwindcss').Config} */
const config = {
darkMode: ["class"],
content: [
"./pages/**/*.{js,ts,jsx,tsx,mdx}",
"./components/**/*.{js,ts,jsx,tsx,mdx}",
"./app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
colors: {
background: "var(--background)",
foreground: "var(--foreground)",
},
fontFamily: {
poppins: ["var(--font-poppins)", "sans-serif"],
gloock: ["var(--font-gloock)", "serif"],
}
},
},
plugins: [],
};
export default config;

Use Fonts

Now we can start using the fonts like this:

/* in globals.css file */
body {
font-family: var(--font-poppins);
}
// in page.js file
<header className="font-gloock">

8. Blog Post Integration

Add Markdown Files

Create markdown files in the articles folder with frontmatter for metadata. Example:

---
title: "First Blog Post"
category: "general"
date: "2024-12-25"
description: "An introduction to markdown blogs."
image: "/image.jpg" ---

Dynamic Blog Post Routes

Create a dynamic route in app/blog/[slug]/page.js. Create a React component called BlogPost in page.js:

const BlogPost = async ({ params }) => {
const { slug } = params;
return (
<div className="text-center p-6">
<h1 className="text-4xl font-bold">Blog Post Page</h1>
<p>Slug: {slug}</p>
</div>
);
};
export default BlogPost;

Now visit this url /blog/abc in the browser. You will see the Blog Post page being rendered, and will also see the slug which is abc.

Extracting Metadata from Markdown Posts

To extract metadata (frontmatter) from markdown files, follow these steps:

  1. Create a lib folder in the project root and add a file named articles.js.
  2. Use the gray-matter package to parse the frontmatter and uuid to generate unique IDs for each post.

Install the required packages:

npm install gray-matter uuid

Writing the Helper Function

With the required packages installed, let’s write the helper function in articles.js to extract metadata (frontmatter) and generate unique IDs for each blog post.

Add the following code to articles.js:

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import { v4 as uuidv4 } from 'uuid';
// Directory containing markdown posts
export const postsDirectory = path.join(process.cwd(), 'articles');
export const getPostMetaData = () => {
// Get all filenames in the posts directory
const files = fs.readdirSync(postsDirectory);
// Filter to include only markdown files
const markdownFiles = files.filter((file) => file.endsWith('.md'));
const posts = markdownFiles.map((filename) => {
// Read the content of each markdown file
const fileContents = fs.readFileSync(`${postsDirectory}/${filename}`, 'utf-8');
// Parse the frontmatter using gray-matter
const metaInfos = matter(fileContents);
// Return an object with a unique ID, slug, and metadata
return {
id: uuidv4(),
slug: filename.replace('.md', ''),
...metaInfos.data,
};
});
return posts;
};

This function reads all markdown files from the articles directory, extracts their metadata, and returns an array of posts with unique IDs, slugs, and frontmatter details.

9. Creating the Blog Listing Page

Let’s use the helper function getPostMetaData to create a dynamic Blog Listing page.

Step 1: Blog Listing Page

In the app/blog/page.js file, import the helper function getPostMetaData and display the blog post metadata.

import { getPostMetaData } from "@/lib/articles"
import Card from "@/components/Card"
const BlogListing = () => {
// Get all post metadata as an array
const postMetaData = getPostMetaData()
return (
<section>
<header className="font-gloock py-6">
<h1 className="text-4xl text-neutral-800 text-center">Blog Listing</h1>
</header>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-5 py-6">
{postMetaData.map((post) => {
const { id, slug, title, category, date, description, image } = post
return (
<Card
key={id}
slug={slug}
title={title}
category={category}
date={date}
description={description}
image={image}
/>
)
})}
</div>
</section>
)
}
export default BlogListing

This code maps through the postMetaData array and passes data to the Card component, which will render individual blog cards.

Step 2: Create the Card Component

Create a new file Card.js in the components directory, and add the following code:

import Image from "next/image"
import Link from "next/link"
const Card = ({ slug, title, description, image }) => {
return (
<article className="group overflow-hidden border bg-white shadow-lg transition-transform duration-300 ease-in-out hover:shadow-2xl">
<Link href={`/blog/${slug}`}>
<Image
alt={title}
src={image}
className="h-56 w-full object-cover transition-filter duration-300 group-hover:filter group-hover:grayscale"
width={300}
height={300}
/>
</Link>
<div className="p-4 sm:p-6">
<Link href={`/blog/${slug}`}>
<h3 className="mt-2 text-xl text-gray-800 font-light hover:text-blue-600">
{title}
</h3>
</Link>
<Link href={`/blog/${slug}`}>
<p className="mt-3 line-clamp-3 text-sm text-gray-600">
{description}
</p>
</Link>
<Link href={`/blog/${slug}`} className="inline-block mt-4 text-sm text-blue-700 hover:underline">
Read more
</Link>
</div>
</article>
)
}
export default Card

Once this setup is complete, navigate to your blog listing URL /blog. You should see your page populated with blog post cards, each displaying metadata and a preview.

Blog Listing page with Card components

10. Single Post Creation and rendering

Step 1: Helper function to get the Single Post data

Create a getSinglePost function in /lib/articles.js to fetch the content of a blog post by its slug.

import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
const postsDirectory = path.join(process.cwd(), 'posts');
export const getSinglePost = (slug) => {
const filename = `${slug}.md`;
const fileContent = fs.readFileSync(`${postsDirectory}/${filename}`, 'utf-8');
return matter(fileContent);
};

Step 2: Install Dependencies

To render markdown content install react-markdown and rehype-raw.

npm install react-markdown rehype-raw
  • react-markdown: Converts markdown content into React components.
  • rehype-raw: Allows rendering raw HTML within markdown (be cautious about security risks).

11. Creating the Blog Post Page

Now let’s set up the dynamic blog post page in app/blog/[slug]/page.js.

Step 1: Generate Dynamic Routes for Each Blog Post

Next.js 15 uses a function called generateStaticParams to create paths for static pages at build time.

  • In Next.js 15, this function is called generateStaticParams, whereas in Next.js 12, it was known as getStaticPaths.
  • Both serve the same purpose: they inform Next.js about all the dynamic routes that need to be pre-rendered at build time.
  • This is crucial for generating a static site, as it allows Next.js to know all possible slugs (or dynamic paths) in advance and create static HTML pages for them.

This is how the function will look like for us

import { getPostMetaData } from '@/lib/articles';
export const generateStaticParams = async () => {
const postMetaData = getPostMetaData();
const data = postMetaData.map((post) => ({ slug: post.slug }));
return data;
};

Step 2: Fetch the Metadata and Content of the Markdown Post

NextJs provides us a function called generateMetadata that helps to dynamically generate the metadata for each blog post for better SEO.

  • This function is specific to Next.js and has a special purpose: to dynamically generate metadata such as the page title, description, and other SEO-friendly attributes based on the current post.
  • For more details, you can refer to the Next.js documentation on generateMetadata.

Use generateMetadata to dynamically generate metadata for each blog post

export const generateMetadata = async ({ params }) => {
const { slug } = params;
const postMetaData = getPostMetaData();
const currentPost = postMetaData.find((post) => post.slug === slug);
if (!currentPost) {
return { title: 'My Blog', description: 'My Blog Description' };
}
return {
title: `${currentPost.title} | My Blog`,
description: currentPost.description,
image: currentPost.image,
keywords: currentPost.category,
date: currentPost.date,
};
};

Step 3: Rendering the Blog Post

Use the getSinglePost helper function to dynamically render blog post content.

import { getSinglePost } from '@/lib/articles';
import ReactMarkdown from 'react-markdown';
import rehypeRaw from 'rehype-raw';
import Link from 'next/link';
import Image from 'next/image';
import { ArrowLeftIcon } from '@heroicons/react/24/outline';
const BlogPost = async ({ params }) => {
// Get slug from params
const { slug } = params;
// Call the getSinglePost function passing slug as the argument
const fileContent = getSinglePost(slug);
// Destructure content and meta data from fileContent
const { content, data: meta } = fileContent;
// Destructure the meta info
const { title, category, date, description, image } = meta;
return (
<>
<div className="flex items-center justify-between text-sm text-gray-500 p-6">
<Link href="/blog" className="flex space-x-4 items-center">
<ArrowLeftIcon className="w-6 h-6" />
<span>All Posts</span>
</Link>
<div className="space-x-4">
<span className="bg-gray-100 text-gray-500 px-2 py-1 rounded">{category}</span>
<span>{new Date(date).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' })}</span>
</div>
</div>
<div className="text-neutral-800 text-center p-6">
<h1 className="font-gloock text-4xl mb-6">{title}</h1>
<p>{description}</p>
</div>
{image && (
<div className="mb-9">
<Image
src={image}
width={600}
height={400}
alt={`Featured image for ${title}`}
className="w-full max-h-[500px] object-cover shadow-md"
/>
</div>
)}
<article>
<ReactMarkdown rehypePlugins={[rehypeRaw]}>{content}</ReactMarkdown>
</article>
</>
);
};
export default BlogPost;

Now you will see the Blog Post being rendered on the page. Notice that the post is not styled.

12. Style the Single Post page

When you render a single blog post, you may notice that it doesn’t look styled by default. Without styling, elements like headings, paragraphs, and lists may appear plain, making the post less visually appealing.

While it’s possible to manually style every tag in your markdown content (e.g., h1, h2, p, ul, etc.), there’s a much easier way if you’re using Tailwind CSS: the Tailwind Typography plugin.

The Tailwind Typography plugin is a utility-based solution for styling content generated from rich text or markdown. It provides a pre-defined class, prose, that automatically styles your content. By adding this class to your article or container, you can instantly make your blog posts look polished and well-structured.

Step 1: Install the Tailwind Typography Plugin

Run the following command in your project directory to install the plugin:

npm install @tailwindcss/typography

Step 2: Configure Tailwind to Use the Plugin

Open your tailwind.config.js file and add the plugin under the plugins section:

module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {},
},
plugins: [
require('@tailwindcss/typography'),
],
};

This tells Tailwind to include the Typography plugin in your build process.

Step 3: Apply the prose Class to Your Article Tag

In your page.js file (where the single post is rendered), find the

tag where the markdown content is rendered. Add the prose class to this tag:

<article className="prose prose-slate max-w-screen-md">
<ReactMarkdown rehypePlugins={[rehypeRaw]}>{content}</ReactMarkdown>
</article>

Here:

  • prose styles the content to look polished.
  • prose-slate changes the color theme to a soft slate gray, but you can experiment with other colors like prose-blue or prose-green.
  • max-w-screen-md limits the article’s width for better readability.

Step 4: Customize the Typography (Optional)

If you want to tweak the default styles, you can use element modifiers to customize the style of individual elements in your content directly in your HTML. For example:

<article className="blogpost prose prose-slate prose-h1:font-gloock prose-h2:font-gloock prose-h2:text-[27px] prose-headings:tracking-wider max-w-screen-md pb-12">
<ReactMarkdown rehypePlugins={[rehypeRaw]}>
{content}
</ReactMarkdown>
</article>

Read more about customization options in this link: Typography Tailwind

Finally the page.js file located at app/blog/[slug]/page.js looks like this:

import { getPostMetaData, getSinglePost } from "@/lib/articles"
import isEmpty from 'lodash/isEmpty'
import ReactMarkdown from 'react-markdown'
import rehypeRaw from 'rehype-raw'
import Image from "next/image"
import Link from "next/link"
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
export const generateStaticParams = async () => {
const postMetaData = getPostMetaData()
const data = postMetaData.map((post) => {
return {
slug: post.slug
}
})
return data
}
export const generateMetadata = async ({ params }) => {
const { slug } = await params;
const postMetaData = getPostMetaData()
const currentPost = postMetaData.find((post) => post.slug === slug)
if (isEmpty(currentPost)) {
return {
title: 'My Blog',
description: 'My Blog Description'
};
}
return {
title: `${currentPost.title} | My Blog`,
description: currentPost.description,
image: currentPost.image,
keywords: currentPost.category,
date: currentPost.date,
category: currentPost.category
};
};
const BlogPost = async ({ params }) => {
const { slug } = await params
const fileContent = getSinglePost(slug)
const { content, data: meta } = fileContent;
const { title, category, date, description, image } = meta
return (
<>
<div className="flex items-center justify-between text-sm text-gray-500 p-6">
<Link href="/blog" className="flex space-x-4 items-center">
<ArrowLeftIcon className="w-6 h-6" />
<span>All Posts</span>
</Link>
<div className="space-x-4">
<span className="bg-gray-100 text-gray-500 px-2 py-1 rounded">{category}</span>
<span>{new Date(date).toLocaleDateString("en-US", {
year: "numeric",
month: "short",
day: "numeric"
})}</span>
</div>
</div>
<div className="text-neutral-800 text-center p-6">
<h1 className="font-gloock text-4xl mb-6">{title}</h1>
<p>{description}</p>
</div>
{image && (
<div className="mb-9">
<Image
src={image}
width="600"
height="400"
alt={`Featured image for ${title}`}
className="w-full max-h-[500px] object-cover shadow-md"
/>
</div>
)}
<article className="blogpost prose prose-slate prose-h1:font-gloock prose-h2:font-gloock prose-h2:text-[27px] prose-headings:tracking-wider max-w-screen-md pb-12">
<ReactMarkdown rehypePlugins={[rehypeRaw]}>
{content}
</ReactMarkdown>
</article>
</>
)
}
export default BlogPost

Following is a preview of how the comppageonent will look on the browser.

Single Blog Post Page