Home >Web Front-end >JS Tutorial >Why Do I Get Fetch Errors When Building a Next.js Static Website in Production?

Why Do I Get Fetch Errors When Building a Next.js Static Website in Production?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 02:22:10663browse

Why Do I Get Fetch Errors When Building a Next.js Static Website in Production?

Error While Generating Static Website for Next.js in Production

Next.js users may encounter fetch errors upon building a static website for production (npm run build) despite having a functional development setup (npm run dev). This issue arises when fetching data from API routes within getStaticProps or getStaticPath functions.

Root Cause

Next.js builds static websites by pre-rendering pages and data on the server before deploying them to a hosting environment. However, API routes, which are typically used for dynamic data retrieval, are not available during the build process because the server is not yet active.

Resolution

To resolve this issue, avoid accessing internal API routes from within getStaticProps/getStaticPath functions. These functions operate exclusively on the server-side and should not rely on external network requests.

Recommended Approach

Instead, directly embed server-side code within getStaticProps/getStaticPath to fetch data from the data source. Since these functions execute on the server, accessing databases or performing server-side operations is permissible.

Example Refactoring

In your provided code, you can find the amended getStaticProps and getStaticPaths functions below:

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 implementing these changes, you can eliminate the fetch errors encountered during production builds.

The above is the detailed content of Why Do I Get Fetch Errors When Building a Next.js Static Website in Production?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn