1

I have tried to touch Next.js 13 (using the App Router) and faced some issues. The structure of my test app is:

---/school
------/app
   ------/layout.tsx
   ------/page.tsx
---/src

The ./app/page.tsx is

async function Page() {

    const hotels = await hotelService.getAllHotels()

    return (
        <RootLayout>
            <HomePage hotels={hotels}/>
        </RootLayout>
    )
}

export default Page

When next build makes collecting page data step the hotelService.getAllHotels() requests data from API by URL address. The URL address is defined by $API_BACKEND_ENV variable and depends on the environment (URL_FRO_DEV=https://1.1.1.1/hotel/all and URL_FRO_PROD=https://2.2.2.2/hotel/all).

The error comes from const res = await fetch(this.url + "/hotel/all", { cache: 'no-store' }) line. If this.url not defined the error is thrown.

How can I avoid the collecting page data and throwing an exception?

NEXT JS docs says the getServerSideProps() is not launched the next build command. I tried to define hotelService.getAllHotels() inside the getServerSideProps() and expected not request the API. But it does not work.

async function Page({ data }) {

    return (
        <RootLayout>
            <HomePage hotels={data}/>
        </RootLayout>
    )
}

export async function getServerSideProps() {
    const data = await hotelService.getAllHotels()  <<< I expect that this line is not launched while the <next build> command
    return {
        props: data
    }
}

export default Page
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
chudnikau
  • 29
  • 1
  • 6

1 Answers1

1

If you want a behavior similar to getServerSideProps that does not run at build time, use the dynamic route config, like so:

// layout.js / page.js / route.js

export const dynamic = "force-dynamic"; //  

async function Page() {
  const hotels = await hotelService.getAllHotels();

  return (
    <RootLayout>
      <HomePage hotels={hotels} />
    </RootLayout>
  );
}

export default Page;

As a side note, getServerSideProps itself won't work inside the app router (directory). Also, route segments only work in layout, page, and route files, not with normal components (like getServerSideProps didn't).

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65