Home > Web Front-end > JS Tutorial > Why Do I Get a 'Fetch Error' When Building My Next.js Static Site in Production?

Why Do I Get a 'Fetch Error' When Building My Next.js Static Site in Production?

Linda Hamilton
Release: 2024-12-03 00:50:16
Original
770 people have browsed it

Why Do I Get a

Fetch Error While Building Next.js Static Website 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.

Internal API Route Usage in getStaticProps

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.

Server-Side Code in getStaticProps and getStaticPaths

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.

Rewritten Code

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,
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template