nextjs: dynamic routes

2022-02-20

 | 

~2 min read

 | 

245 words

NextJS includes built-in support for Dynamic Routes.

This is great, but sometimes things go awry and unfortunately the errors aren’t particularly easy to parse.

For example, I had a dynamic route:

.
└── pages
    └── [blogPost].tsx

But, I was getting an error:

error - Error: A required parameter (blogPost) was not provided as a string in getStaticPaths for /[blogPost]

Initially, I was confused because I seemed to be passing up the props:

[blogPost].tsx
export async function getStaticPaths() {
  const dir = await fs.readdir(path.join(NOTES_PATH));
  const filteredFiles = await filterAsync(dir, (fileName) =>
    fileFilter(NOTES_PATH, fileName)
  );
  const filesFrontmatter = await mapAsync(filteredFiles, extractFrontmatter);

  const paths = filesFrontmatter.map((frontmatter: PostFrontmatter) => ({
    params: {
      slug: frontmatter.slug,
      fileName: frontmatter.fileName,
    },
  }));
  return {
    paths,
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  console.log({ params });

  return { props: {} };

The issue, it turned otu was my choice of name for the dynamic route.

The name [blogPost] isn’t random. It’s necessary.

See, what I’d missed was in the props I was passing up, none of them were titled blogPost.

I could have updated my paths variable to be:

const paths = filesFrontmatter.map((frontmatter: PostFrontmatter) => ({
  params: {
    blogPost: frontmatter.slug,
    fileName: frontmatter.fileName,
  },
}))

Or, if I liked the shape of the object, I could change the file name to [slug].tsx. Then the required prop would have been provided.

Credit to Homu in the NextJS Discord for pointing me in the right direction.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!