Static Rendering Server Components in Next.js
For this website, I wanted to use Next.js to statically render the each of the notes. The notes are in a directory path with a Dynamic Segment. I’m using the latest version of Next.js, which is 13.4 at the time of writing.
Next.js rolled out Server Components, along with the new app directory structure. The old method was to use the getStaticPaths and getStaticProps functions to statically render the pages. With the new app directory structure, you can use React Server Components to statically render the pages.
The Server Component uses an async function loadBlogPost to load the data from the file system. Within the function, React.cache is used to cache the data.
const Page = async ({ params }: Props) => {
const { title, content } = await loadBlogPost(params.postSlug);
return (
<article>
<h1>{title}</h1>
<MDXRemote source={content} />
</article>
);
};
export default Page;
Since the route uses a Dynamic Segment, the generateStaticParams function is used to generate the static paths. The function uses the getBlogPostList function to get the list of blog posts. The function returns an array of objects with the postSlug property.
export async function generateStaticParams() {
const posts = await getBlogPostList();
return posts.map((p) => ({
postSlug: p.slug,
}));
}
You can also control the fallback behavior with exporting the dynamicParams property.
export const dynamicParams = true // true | false,
And that’s it! The pages are statically rendered. The next build command shows that the pages are statically rendered.
Route (app) Size First Load JS
┌ ○ / 145 B 78.6 kB
├ ● /[postSlug] 145 B 78.6 kB
├ ├ /discriminated-unions
├ ├ /nullish-coalescing
├ ├ /spring-in-action-notes
├ └ [+2 more paths]
...
○ (Static) automatically rendered as static HTML (uses no initial props)
● (SSG) automatically generated as static HTML + JSON (uses getStaticProps)