#How can i make a component dynamic?

1 messages · Page 1 of 1 (latest)

jovial gull
#

During the build proces I'm receiving errors from data calls to APIs that are not available during the build proces. How do I prevent these? Example error: Collecting page data ...
33.30 [Error: Failed to collect configuration for /[locale]/shop/[stockCode]/[parcelCode]] {

leaden finchBOT
#

Hi @jovial gull. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To make a component dynamic and prevent errors from API calls during the build process, you have several options in Next.js:

Using the dynamic route segment config

The most straightforward approach is to add the dynamic route segment configuration to your page or layout file:

export const dynamic = 'force-dynamic';

export default function Page() {
  // Your component code with API calls
  return <div>{/* content */}</div>;
}

This forces dynamic rendering at request time rather than during the build process, which prevents errors from unavailable APIs during build time. The force-dynamic option ensures your page is rendered for each user at request time, similar to how getServerSideProps worked in the Pages Router as explained in the Next.js documentation.

Alternative approaches

  1. Wrap async components with Suspense:
    import { Suspense } from 'react'
    
    export default function Page() {
      return (
        <div>
          <h1>Static content</h1>
          <Suspense fallback={<p>Loading...</p>}>
            <DynamicComponent />
          </Suspense>
        </div>
      )
    }
    
    This tells Next.js to use the fallback until the promise resolves as recommended in Vercel's documentation.
#
  1. Use next/dynamic with ssr: false to completely disable server-side rendering for a component:
    import dynamic from 'next/dynamic'
    
    const ClientOnlyComponent = dynamic(() => import('./component'), {
      ssr: false,
    })
    
    This is useful for components that rely on browser APIs and should only render in the browser as shown in the Next.js documentation.

For your specific error with dynamic routes

Since your error involves dynamic routes (/[locale]/shop/[stockCode]/[parcelCode]), you should add the dynamic configuration to the page file within that route structure:

// In your page.tsx file for this route
export const dynamic = 'force-dynamic';

export default function ProductPage() {
  // Your component code
}

This approach has been confirmed to work in similar situations as mentioned in a GitHub issue where adding export const dynamic = 'force-dynamic' resolved build errors related to API connections.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@jovial gull Kapa.ai is still learning and improving, please let me know how I did by reacting below.