data fetching from dynamic route getting 404 error in nextjs v13.4 page router. Any help
Unanswered
Five-striped Sparrow posted this in #help-forum
Five-striped SparrowOP
export const getStaticPaths = async () => {
// Generate the paths for all product IDs
const all_products = await fetch("http://localhost:3000/api/products");
const res = await all_products.json();
const products = res.data;
const paths = products.map((product) => ({
params: { productDetails: product._id },
}));
// Return the paths to Next.js
return {
paths,
fallback: false, // Or "blocking" or "true" depending on your use case
};
};
export const getStaticProps = async (context) => {
try {
const { params } = context;
const product = await fetch(
);
const productDetailsData = await product.json();
console.log("productDetailsData", productDetailsData.data[0]);
return {
props: { productDetails: productDetailsData.data[0] },
// revalidate: 3600, // Optional: Time in seconds to revalidate (cache revalidation)
};
} catch (error) {
console.error("Error fetching data:", error);
return {
props: { productDetails: {} },
};
}
};
// Generate the paths for all product IDs
const all_products = await fetch("http://localhost:3000/api/products");
const res = await all_products.json();
const products = res.data;
const paths = products.map((product) => ({
params: { productDetails: product._id },
}));
// Return the paths to Next.js
return {
paths,
fallback: false, // Or "blocking" or "true" depending on your use case
};
};
export const getStaticProps = async (context) => {
try {
const { params } = context;
const product = await fetch(
http://localhost:3000/api/products/${params?.productDetails});
const productDetailsData = await product.json();
console.log("productDetailsData", productDetailsData.data[0]);
return {
props: { productDetails: productDetailsData.data[0] },
// revalidate: 3600, // Optional: Time in seconds to revalidate (cache revalidation)
};
} catch (error) {
console.error("Error fetching data:", error);
return {
props: { productDetails: {} },
};
}
};
3 Replies
Tramp ant
I think calling api from a server component is not recommended. You should use the same logic you use within your api in your server component. Either by abstracting the logic into its own function or by importing the GET function from your api:
https://github.com/vercel/next.js/issues/48344#issuecomment-1629677522
https://github.com/vercel/next.js/issues/48344#issuecomment-1629677522
what koan said is completely correct, although to clear any confusion, what is said for 'server component' here can also be applied for getStaticPaths and getStaticProps which the OP used
Five-striped SparrowOP
thanks for the reply, I'll check it out