Slug always shows 404 Error
Answered
Bald Eagle posted this in #help-forum
Bald EagleOP
Hi I am trying to figure out why my blog slug always returns a 404.
I don't think it's the slug id issue.
I don't think it's the slug id issue.
8 Replies
Bald EagleOP
import { GetStaticProps, GetStaticPaths } from "next";
import { useRouter } from "next/router";
import client from "./components/contentfulClient";
export const getStaticPaths: GetStaticPaths = async () => {
try {
const response = await client.getEntries({
content_type: "blogPost",
select: "fields.slug",
});
const paths = response.items.map((item) => ({
params: { slug: item.fields.slug },
}));
return {
paths,
fallback: "blocking", // Will wait for the page to be generated on request if not found
};
} catch (error) {
// Log and handle errors
console.error("Error fetching slugs from Contentful:", error);
return { paths: [], fallback: "blocking" };
}
};
export const getStaticProps: GetStaticProps = async ({ params }) => {
try {
const { slug } = params;
const response = await client.getEntries({
content_type: "blogPost",
"fields.slug": slug,
limit: 1,
});
if (!response.items.length) {
// Redirect to the blog list if the post is not found
return {
redirect: {
destination: "/blog",
permanent: false,
},
};
}
const post = response.items[0].fields;
return {
props: { post },
revalidate: 1, // ISR will revalidate the page every second
};
} catch (error) {
console.error(
"Error fetching data from Contentful for slug:",
params.slug,
error
);
return {
redirect: {
destination: "/blog",
permanent: false,
},
};
}
};should be
src/app/blog/[slug]/page.tsxBald EagleOP
so my slug should be another folder?
yes
every page need to be named
page.tsxAnswer
Bald EagleOP
Okay I got it. thanks!
please mark solution if your issue has been solved