typescriptintermediate
generateStaticParams for Dynamic Routes
Pre-render dynamic routes at build time using generateStaticParams with fallback handling.
typescriptPress ⌘/Ctrl + Shift + C to copy
// app/blog/[slug]/page.tsx
import { notFound } from 'next/navigation';
interface Post {
slug: string;
title: string;
content: string;
}
async function getPost(slug: string): Promise<Post | null> {
const res = await fetch(`https://api.example.com/posts/${slug}`, {
next: { revalidate: 3600 },
});
if (!res.ok) return null;
return res.json();
}
export async function generateStaticParams() {
const res = await fetch('https://api.example.com/posts');
const posts: Post[] = await res.json();
return posts.map((post) => ({ slug: post.slug }));
}
export const dynamicParams = false;
export default async function BlogPost({
params,
}: {
params: Promise<{ slug: string }>;
}) {
const { slug } = await params;
const post = await getPost(slug);
if (!post) notFound();
return (
<article>
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</article>
);
}Use Cases
- blog pages
- product pages
- static site generation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Catch-All and Optional Catch-All Routes
Handle dynamic nested routes with catch-all [...slug] and optional [[...slug]] segments.
Best for: documentation sites
#nextjs#routing
typescriptintermediate
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Best for: CRUD API endpoints
#api#route-handler
typescriptintermediate
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Best for: Dashboard access control
#middleware#authentication
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms