Tailwind Logo

Using Nextjs' App Route's Dynamic Routes to create blog pages (Part 2)

Content Hub ONENext.js

Published: 2024-08-22

In the last issue, we showed you how to create a Dynamic Route for an individual blog page using an ID. This time, we will make one more improvement and proceed so that the URL paths can be processed using dates and Slug.

Check the slug and date

We will check whether we can get the PublishDate and Slug in the blog post that was only displaying the title last time by modifying the app/blog/[slug]/page.tsx file.

TypeScript
  return (
    <>
      <div>Title: {post.title}</div>
      <div>Publish Date: {post.publishDate}</div>
      <div>Slug: {post.slug}</div>
    </>
  );

The actual publishDate and slug will be displayed.

nextappdynamicroute05.png

I have confirmed that the necessary data has been obtained on the page.

Switch from ID to Slug

We will change the value used as the URL from the ID to the Slug value. First, in order to display the blog post using the Slug, we will create a query to retrieve the blog post with the same Slug value. In this case, we created the following using a sample post.

GraphQL
query AllBlog {
    allBlog(where: { slug_eq: "introducing-sitecore-composable-dxp-products" }) {
        total
        results {
            description
            id
            name
            publishDate
            slug
            title
            body
            image {
                total
                results {
                    description
                    fileHeight
                    fileId
                    fileName
                    fileSize
                    fileType
                    fileUrl
                    fileWidth
                    id
                    name
                }
            }
        }
    }
}

You can see that the data has been retrieved using Postman as follows.

nextappdynamicroute02.png

We will add a definition for making a call to src/interfaces/Blog/index.ts.

TypeScript
export const BlogFromSlugQuery = (slug: string) => {
  return `
  query AllBlog {
    allBlog(where: { slug_eq: "${slug}" }) {
        total
        results {
            description
            id
            name
            publishDate
            slug
            title
            body
            image {
                total
                results {
                    description
                    fileHeight
                    fileId
                    fileName
                    fileSize
                    fileType
                    fileUrl
                    fileWidth
                    id
                    name
                }
            }
        }
    }
}
  `
}

In the above, we passed the slug value and made the call. This query retrieves all blog posts with the same slug value. For this reason, we will set a unique value for the slug. Next, add the following code to src/utils/getBlog/index.ts, which defines the function for retrieving posts.

TypeScript
export async function getBlogFromSlug(slug: string): Promise<Partial<Blog>> {
    const results: AllBlogResponse = (await fetchGraphQL(
        BlogFromSlugQuery(slug)
    )) as AllBlogResponse;

    return results.data.allBlog.results[0];
}

This makes it possible to retrieve the relevant article using the slug. Even if the slug is registered multiple times, it will retrieve the first result.

Now, in order to actually use slug in the URL, change the code that retrieves the page in the app/blog/[slug]/page.tsx file as follows.

TypeScript
  const post = await getBlogFromSlug(params.slug);

This will display the page using the Slug value. To make it easier to test, change the output section of the top page's app/page.tsx file as follows.

TypeScript
    <main>
      <h1>Content Hub ONE - Title list</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <Link href={`/blog/${post.slug}`}>{post.title}</Link>
          </li>
        ))}
      </ul>
    </main>

When you run it, you can see that the blog page is displayed using slug as follows.

nextappdynamicroute06.png

Set the date in the URL

Finally, I want to set up Dynamic Routes so that I can set the URL in the form YYYY/MM/DD/Slug, not just Slug. To enable the use of multiple paths, I will use Catch-all Segments, so I will change the path to [...slug].

In the file src/app/blog/[...slug]/page.tsx after the change, the fourth value is treated as slug, so rewrite it as follows to get slug with params.slug[3].

TypeScript
export default async function Page({ params }: { params: { slug: string } }) {
  const post = await getBlogFromSlug(params.slug[3]);

Now you can specify dates and other information and include them in the URL.

nextappdynamicroute04.png

Summary

This time, we introduced the procedure for adding a field to be used as a Slug so that you can control the URL. However, we have only specified the date, and for now we have not specified anything. We will implement this next time. The content displayed as an example is only the title, but since it is possible to obtain the data, we will create a blog page.

Related article

Tags