How to feed data from a Route Handler to a client component in Next.JS App Router?

  Kiến thức lập trình

In a Next.JS 14 project, I have a client component that resides at /app/loc/page.js, and a router handler, which resides at /app/loc/api/route.js, that should fetch data and deliver it to the aforementioned client component.

What I need is to fetch the data in such a way that when loading the client component, the data shall be already there. Previously, in the old /pages routing, this was being achieved through getStaticProps, and the data was ready to be used whenever the client component was mounted, due to the fact that it was present in the data prop of the component.

How can this behavior be achieved in the new /app routing using Route Handlers?

Since you want “the data shall be already there” you should use a server component instead. And if you want you can inside put your client component.

const ServerComp = async () => {
  const props = await fetch(...)

  return (
    <ClientComponent {...props} />
  )
}

The await fetch is kind of the equivalent of your getStaticProps.

more info here.

LEAVE A COMMENT