Search code examples
next.jsnextjs14

NextJS v14 build errors with fetch


  • to reproduce : NextJS v14.2.3 with app router. Make a http call with fetch on an external API.

  • current behavior: if the API is not available at build time, there's a pre-render error, and the build fails. If cache: 'no-store' is set, then the build succeed, or if the fetch is wrapped inside a try/catch. And i want cache at runtime, so cache: 'no-store' is not an option for me. Why this behaviour ? I can understand that local data could be cached, but why externals apis are called during build time ?


Solution

  • Next.js pre-renders pages at build time to generate static HTML for performance and SEO. During this process any data fetching (like using fetch) is executed at build time to get the data needed for the static pages. So, if the external API is unavailable at build time, the fetch operation fails, leading to a pre-render error and causing the build to fail.

    Solution 1; If the data is not needed for SEO or initial page load, you can fetch it on the client side.

    Solution 2; Use environment variables to check if you are in a build environment and use mock data if the API is unavailable.