Home >Web Front-end >JS Tutorial >Why Do I Get a 'Fetch Error' When Building My Next.js Static Site in Production?
When building a Next.js website for production, you may encounter a "Fetch error" when using getStaticProps and getStaticPaths to fetch data from an API route. This error can occur for a couple of reasons.
In the provided code, you are calling an internal API route, /api/products/${slug}, from within getStaticProps. This is not recommended because API routes are not available during build time, leading to the fetch error.
Instead of fetching an API route, you should write server-side code directly in getStaticProps and getStaticPaths. These only run server-side and allow you to write code directly using server-side resources like database queries.
Here's a modified version of your code:
// /pages/product/[slug] import db from '../../../data/products' // Remaining code.. export const getStaticProps = async ({ params: { slug }, locale }) => { const result = db.filter(item => item.slug === slug) const data = result.filter(item => item.locale === locale)[0] const { title, keywords, description } = data return { props: { data, description, keywords, title } } } export const getStaticPaths = async () => { const paths = db.map(({ slug, locale }) => ({ params: { slug: slug }, locale })) return { fallback: true, paths, } }
By using the data source directly in getStaticProps and getStaticPaths, you avoid calling internal API routes during build time, resolving the fetch error.
The above is the detailed content of Why Do I Get a 'Fetch Error' When Building My Next.js Static Site in Production?. For more information, please follow other related articles on the PHP Chinese website!