[Fixed] NextJs 13 App Router – Error occurred prerendering page. TypeError: fetch failed – Javascript

by
Ali Hasan
app-router next.js vercel

Quick Fix: Remove the getdata() function fetching to the client side before build. Re-add it afterwards and everything should work perfectly.

The Problem:

A Next.js 13 application is experiencing an error during prerendering on the /feeds page, resulting in a production deployment failure on Vercel. The error message indicates a failed attempt to fetch data from an API endpoint, but the same code works flawlessly in the development environment.

The Solutions:

Solution 1: Remove Data Fetching Before Build

Next App router’s API routes are inaccessible until after build. To resolve this issue:

  1. Comment out the `getData` function that fetches data on the client side before building.
  2. Build the project. The build should now be successful without any errors.
  3. Re-add the `getData` function.

This approach ensures that the API routes are built before the client-side code, preventing fetch errors during production.

Solution 2:

During build time, accessing Next.js API routes is not allowed. To resolve this, you have two options:

  1. Execute the fetching logic inside the getData function:

    Move the fetching logic directly into the getData function, eliminating the API route call.

  2. Fetch posts from an external URL:

    If possible, retrieve the posts from an external URL that is available during build time, such as a static JSON file or a public API.

Q&A

What’s causing my NextJs 13 App Router project to crash during production (deployed on Vercel via github) with the error ‘TypeError: fetch failed’?

Next.js API routes are inaccessible until after build. Remove the ‘getdata’ fetch function before build, re-add it afterwards, and build the API routes first.

Is it possible to use Next.js API routes during build?

No, Next.js API routes are not accessible during build. Fetch the data directly inside the ‘getData’ function or from an external URL.

Video Explanation:

The following video, titled "Error occurred prerendering page | build export encountered error in ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Josh tried coding•28K views · 14:32 · Go to channel · Next.js App Router: Routing, Data Fetching, Caching. Vercel•252K views · 9:31 · Go to ...