Up until now, we have been using Dynamic Routes to determine the URL of the blog, and we have created the fourth path as a Slug. This time, we will use the date to determine the path as well.
Using Nextjs' App Route's Dynamic Routes to create blog pages (Part 3)
Content Hub ONENext.jsPublished: 2024-08-23
Add generateStaticParams
In order to use the date, we will use the react-moment package to process the date. So, we will add it to the project.
npm install react-moment
After installation is complete, add generateStaticParams. The process is to retrieve all blog posts, store the values that will become the path in staticParams, and return them to generate the static page. For this code,
export const dynamicParams = false;
the page will be considered to be missing. Please add the following code to src/app/blog/[...slug]/page.tsx.
import moment from "moment";
export const dynamicParams = false;
export async function generateStaticParams() {
const posts = await getAllBlog();
const staticParams: { slug: string[] }[] = [];
posts.map((post) => {
const yearmonthdate = post.publishDate?.slice(0, 10);
const blogUrlDate = moment(yearmonthdate);
staticParams.push({
slug: [
blogUrlDate.format("YYYY"),
blogUrlDate.format("MM"),
blogUrlDate.format("DD"),
post.slug || "undefined",
],
})
});
return staticParams;
}
As a test, you can now access the blog post by entering the correct URL.
If you specify an incorrect date, an error will be displayed.
Link URL generation function
The link to the blog post is generated by combining the publishDate and slug, so we've prepared an additional function that can generate the link if the target blog is known, so that it can be easily created. Create a file src/utils/url/index.ts and set the code as follows.
import { Blog } from "@/interfaces/Blog";
import moment from "moment";
export function getBlogUrl(post: Partial<Blog>) {
const yearmonthdate = post.publishDate?.slice(0, 10);
const blogUrlDate = moment(yearmonthdate);
return (
"/blog/" +
blogUrlDate.format("YYYY") +
"/" +
blogUrlDate.format("MM") +
"/" +
blogUrlDate.format("DD") +
"/" +
post.slug
);
}
This is loaded in the top page src/app/page.tsx.
<main>
<h1>Content Hub ONE - Title list</h1>
<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={getBlogUrl(post)}>{post.title}</Link>
</li>
))}
</ul>
</main>
Now it is easy to obtain the URL of a blog if you have the information for a blog post.
Summary
I went through the process of loading a blog and generating a URL in three parts. This procedure can be applied in various ways, so it's a good idea to remember it as a basic procedure.
Related article
- Using Nextjs' App Route's Dynamic Routes to create blog pages (Part 1)
- Using Nextjs' App Route's Dynamic Routes to create blog pages (Part 2)
- Using Nextjs' App Route's Dynamic Routes to create blog pages (Part 3)