Dynamic Routes & getStaticPaths

Explain how to create dynamic routes using the file system by adding square brackets to page filenames and retrieve static paths with getStaticPaths.
// In the file pages/posts/[id].js
import { useRouter } from 'next/router';

const Post = () => {
  const router = useRouter();
  const { id } = router.query;

  return <p>Post: {id}</p>;

export default Post;
This creates a dynamic route for individual posts in a Next.js application. The filename uses square brackets to indicate a dynamic segment of the path. The useRouter hook from Next.js is used to access the dynamic parts of the URL (in this case, the post id), which are used within the component to display or fetch data.
// In the same file pages/posts/[id].js
export async function getStaticPaths() {
  // Here you would fetch the list of post IDs from an API
  // or some other source like a database or filesystem.
  const paths = [{ params: { id: '1' } }, { params: { id: '2' } }];

  return { paths, fallback: false };
The getStaticPaths function is used to generate the paths that Next.js will statically pre-render. In this example, it's returning hard-coded paths for post IDs '1' and '2'. For a real application, you would fetch an array of post IDs from a data source. fallback: false ensures that paths not returned by getStaticPaths result in a 404 page.