Next Js Guide

Learn how to integrate Leafpad Blogs into your Next.js 13+ App Router project with step-by-step examples for routing, SSG/ISR, SEO metadata, and dynamic blog


Get the benefit of server side components and level up your seo game. This guide assumes you're using app router. If you're using pages router. The guide would be more or less the same. If you encounter any issue reach out to us

Step 1: Install leafpad Package

npm install @leafpad/blogs
# or pnpm add @leafpad/blogs
# or yarn add @leafpad/blogs

Step 2: Folder Structure

/app
  /blogs
    /[slug]
      page.tsx
    page.tsx
    layout.tsx     
  layout.tsx
  globals.css

Step 3: Create Root Layout

File: /app/blogs/layout.tsx

You can use this page to create basic layout for your blogs section like header, footer and also import the base style here.

The base style only has the bare bones for layout and font size. No colors are applied. Colors are inherited directly from the project

import Footer from "~/components/footer";
import Header from "~/components/header";
import '@leafpad/blogs/src/styles/style.css'
import type { Metadata } from "next";

export const metadata: Metadata = {
  title: "My awesome site",
  description: "My awesome site description",
}

export const revalidate = 43200; // Revalidate every 12 hours

export default function BlogLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return <div>
    <Header />
      <div className="max-w-6xl mx-auto min-h-screen px-4 sm:px-6 lg:px-8 py-0">
        {children}
      </div>
    <Footer />
  </div>
}

File: /app/blogs/page.tsx

Use this to render the base of your layout. Leafpad ships with a default layout. You can use it or you can design your own. There is no restriction here

import { BlogPostFormat, BlogsService } from "@leafpad/blogs";

const blogsApi = new BlogsService('my-awesome-blog')


export default async function BlogsPage() {
  
  // fetch blog post
  const {post} = await await blogsApi.fetchPosts({
     includeHtml: true
  });

  <div
     dangerouslySetInnerHTML={{ 
        __html: BlogPostFormat.blogCards({ 
          posts, 
          urlPrefix: '/blogs' 
        }) 
      }} 
    />
}

Yaay! You have successfully integrated the blogs home page in your site. Lets move on to the individual page for blogs

Individual Blog Page

File Path: /app/blogs/[slug]/page.tsx

You can copy and paste this exact code and your individual page is ready. As always you're not restricted to design leafpad ships with you can always customize the design.

import { BlogPostFormat, BlogsService } from "@leafpad/blogs";
import type { Metadata } from "next";
import { notFound } from "next/navigation";
import TOC from "./_TOC";


export const revalidate = 43200; // Revalidate every 12 hours

const blogsApi = new BlogsService('awsome-app')

export async function generateMetadata({ params }: PageProps<'/blogs/[slug]'>): Promise<Metadata> {

  const { slug } = await params;
  const post = await blogsApi.fetchBlog(slug, { includeHtml: true });
  if (!post) {
    return {
      title: "Post Not Found",
      description: "The requested blog post could not be found.",
    };
  }
  const seoData = post.seo;
  const title = seoData?.title || post.name;
  const description = seoData?.description;
  const image = seoData?.image || "/og-blog.jpg";
  return {
    title: `${title} | Blog`,
    description,
    keywords: seoData?.keywords || post.tags?.map((tag: any) => tag.name),
    authors: [{ name: post.createdByUser.name }],
    openGraph: {
      title,
      description,
      type: "article",
      url: `/blogs/${post.slug}`,
      images: [
        {
          url: image,
          width: 1200,
          height: 630,
          alt: title,
        },
      ],
      publishedTime: new Date(post.createdAt).toISOString(),
      modifiedTime: new Date(post.updatedAt).toISOString(),
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [image],
    },
  };
}

export default async function BlogPostPage({ params }: PageProps<'/blogs/[slug]'>) {
  const { slug } = await params;
  const post = await blogsApi.fetchBlog(slug, { includeHtml: true });
  if (post) {
    return <div>
      <div dangerouslySetInnerHTML={{ __html: BlogPostFormat.blogPostWithToc({post}) }} />
      <TOC />
    </div>;
  }
  return notFound()
}

export async function generateStaticParams() {
  try {
    const res = await blogsApi.fetchPosts({});
    return res.posts.map((post) => ({ slug: post.slug }));
  } catch (error) {
    return [];
  }
}

Optional Scroll Listener for TOC

'use client'

import { BlogUtils } from "@leafpad/blogs"
import { useEffect } from "react"



export default function TOC() {
  useEffect(() => {
    const {destroy} = BlogUtils.attachTocListener('toc')
    return destroy
  }, [])
  return null;
}

You have successfully integrated server side blogs into your site. It would have hardly taken more than 5 mins to complete it. You can start publishing blogs and optimize your sites performance.

You can further read about how to revalidate pages in next js as soon as content is updated in leafpad using webhooks

Published with LeafPad