'Error: A required parameter (slug) was not provided as a string in getStaticPaths for /posts/[slug]

I have the following [slug].js file in my project:

import Head from "next/head";
import PostContent from "../../components/posts/post-detail/post-content";
import { getPostByName, getAllPosts } from "../../helpers/api-util";

function PostDetailPage(props) {
  const post = props.selectedPost;
  console.log(post);
  if (!post) {
    return (
      <div className="">
        <p>Loading...</p>
      </div>
    );
  }
  return <PostContent post={post.slug} />;
}


export async function getStaticProps(context) {
  const blogSlug = context.params.slug;
  const post = await getPostByName(blogSlug);
  return {
    props: {
      selectedPost: post,
    }, // will be passed to the page component as props
  };
}

export async function getStaticPaths() {
  const posts = await getAllPosts();
  const paths = posts.map(post => ({ params: { blogSlug: post.slug } }));

  return {
    paths: paths,
    fallback: "blocking",
  };
}

export default PostDetailPage;

This is my file structure:

enter image description here

I am getting my data from firebase with the following data structure:

enter image description here

The idea is that when I click my post on the 'all posts' page, I get into the PostContent component that contains all my post info.

Once I try to click on a particular post, I am getting the error mentioned in the subject.

Slug is not a string so I am not entirely sure why I am getting this.

Thanks



Solution 1:[1]

You have mismatch between filename dynamic key and what you expect in the code.

You return blogSlug key in getStaticPaths:

const paths = posts.map(post => ({ params: { blogSlug: post.slug } }));

but your file is named [slug].js and you expect a slug key here in getStaticProps:

const blogSlug = context.params.slug;

It should be consistent, in this case it should be named slug everywhere.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1