Fetch error when building Next.js static website in production

From Next.js documentation:

You should not use fetch() to call an API route in getStaticProps. Instead, directly import the logic used inside your API route. You may need to slightly refactor your code for this approach. Fetching from an external API is fine!

You can safely use your API logic directly in getStaticProps/getStaticPaths as these only happen server-side.

Note that getStaticProps runs only on the server-side. (...) That means you can write code such as direct database queries without them being sent to browsers.

Furthermore, your API routes are not available during build-time, as the server has not been started at that point.


Here's a small refactor of your code to address the issue.

// /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,
    }
}