Search code examples
next.jsnext.js14app-router

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


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?


Solution

  • Since you want "the data shall be already there" you should use in your page a server component instead. And if you want you can inside put your client component.

    Also you don't have to create a API route if not needed and run the server code directly there

    const getProps = async () => {
      return // run server side here
    }
    
    const ServerComponent = async () => {
      const props = await getProps()
    
      return (
        <ClientComponent {...props} />
      )
    }
    

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

    more info here.