<- Back to all posts

Mastering Dynamic Routing with Next.js and SleekCMS

Mastering Dynamic Routing with Next.js and SleekCMS

Dynamic routing is a powerful feature in Next.js that allows developers to create pages based on dynamic data. In this post, we will explore how to implement dynamic routing using the app/blog/[slug]/page.tsx file in a Next.js application, leveraging @sleekcms/client to manage content effortlessly.

Understanding Dynamic Routing in Next.js

Dynamic routing in Next.js enables the creation of pages that can respond to different URL parameters. The [slug] in the file path app/blog/[slug]/page.tsx indicates that this file will handle requests for any blog post identified by its unique slug.

Step 1: Setting Up the File Structure

To begin, ensure your Next.js project has the following directory structure:

/app
  /blog
    /[slug]
      page.tsx
/lib
  sleekcms.ts

This structure allows Next.js to recognize that any URL matching /blog/{slug} should render the page.tsx component.

Step 2: Setting Up the SleekCMS Client

First, create a client helper in lib/sleekcms.ts using the @sleekcms/client package:

import { createAsyncClient } from '@sleekcms/client'

export function cmsClient() {
  return createAsyncClient({
    siteToken: "pub-xxxxx-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // Your public site token
    resolveEnv: true,
    env: "latest",
    cacheMinutes: 1,
  })
}

Step 3: Fetching Data from SleekCMS

With the Next.js App Router, we use async Server Components and generateStaticParams for static generation. Here's how to implement the dynamic blog post page:

import { notFound } from 'next/navigation'
import { cmsClient } from '@/lib/sleekcms'

type Props = {
  params: Promise<{ slug: string }>
}

export async function generateStaticParams() {
  const client = cmsClient()
  const slugs = await client.getSlugs('/blog')

  return slugs.map((slug: string) => ({
    slug,
  }))
}

export default async function BlogPostPage({ params }: Props) {
  const { slug } = await params
  const client = cmsClient()
  const post = await client.getPage(`/blog/${slug}`)

  if (!post) {
    notFound()
  }

  return (
    <article>
      <h1>{post.title}</h1>
      {post.content && (
        <div dangerouslySetInnerHTML={{ __html: post.content }} />
      )}
    </article>
  )
}

Step 4: Listing All Blog Posts

To display a list of all blog posts on your homepage, use client.getPages():

import Link from "next/link";
import { cmsClient } from "@/lib/sleekcms";

export default async function HomePage() {
  const client = cmsClient();
  const posts = await client.getPages("/blog/");

  return (
    <ul>
      {posts.map((post: any) => (
        <li key={post._path}>
          <Link href={post._path}>
            <h2>{post.title}</h2>
          </Link>
        </li>
      ))}
    </ul>
  );
}

Step 5: Managing Content with SleekCMS

SleekCMS simplifies the content management process for non-technical authors. When a new blog post is created in the SleekCMS dashboard, the author simply needs to provide a title and content, and the system automatically generates a unique slug based on the title.

For example, if an author creates a blog post titled "Understanding Dynamic Routing," SleekCMS will generate a slug like understanding-dynamic-routing. This slug is then used in the URL, allowing users to access the post at /blog/understanding-dynamic-routing.

Conclusion

By following these steps, you can effectively implement dynamic routing in your Next.js application using @sleekcms/client. This approach leverages Next.js App Router's async Server Components for clean, efficient data fetching directly in your components. Combined with SleekCMS, you get a streamlined content management experience with clean URLs for each blog post.