How to use PMKIN with Next.js (App Router)
This guide uses the App Router approach to integrate PMKIN with your Next.js application. All the code for this quick start guide is in our Next.js quick start repository on GitHub.
Start by adding the necessary packages to your Next.js project:
npm install pmkin react-markdown
Set up your PMKIN API key as an environment variable. Create a .env.local file in your project root:
PMKIN_API_KEY=your_api_key_here
Create a new file app/lib/lib.ts:
import { PmkinClient } from 'pmkin'
if (!process.env.PMKIN_API_KEY) {
throw new Error('PMKIN_API_KEYis not set')
}
export const pmkin = new PmkinClient({
token: process.env.PMKIN_API_KEY
})
Create a new file app/blog/page.tsx:
import Link from 'next/link'
import { pmkin } from '@/lib/pmkin'
export default async function BlogList() {
const documents = await pmkin.listDocuments()
return (
<div>
<h1>Blog Posts</h1>
{documents.map(doc => (
<article key={doc.id}>
<h2>
<Link href={`/blog/${doc.slug}`}>{doc.title}</Link>
</h2>
</article>
))}
</div>
)
}
Create a new file app/blog/[slug]/page.tsx:
import { notFound } from 'next/navigation'
import Markdown from 'react-markdown'
import { pmkin } from '@/lib/pmkin'
interface PageProps {
params: {
slug: string
}
}
export async function generateMetadata({ params }: { params: { slug: string } }): Promise<Metadata> {
const document = await pmkin.findDocumentBySlug(
decodeURIComponent(params.slug)
)
if (!document) {
return {
title: 'Not found',
description: 'This blog post could not be found.'
}
}
return {
title: document.metaTitle ?? document.title,
description: document.metaDescription,
}
}
export default async function BlogPost({ params }: { params: { slug: string } }) {
const document = await pmkin.findDocumentBySlug(
decodeURIComponent(params.slug)
)
if (!post) {
notFound()
}
return (
<article>
<h1>{document.title}</h1>
<ReactMarkdown>{document.markdown}</ReactMarkdown>
</article>
)
}
This setup provides a solid foundation for integrating PMKIN with your Next.js application using the App Router. Using PMKIN's API, you can expand on this by adding pagination, categories, or search functionality.
Note that in the App Router approach, we use React Server Components for data fetching, allowing us to fetch data directly in the component without getStaticProps or getServerSideProps. The generateMetadata function dynamically generates metadata for each blog post.