reactjsnext.jsnext.js13react-server-components

NextJS 13 - how to get NextApiRequest object in async component?


According to the NextJS 13 documentation, writing the async components is the new way of prefetching some data on the server - all the getStaticProps, getInitialProps, and getServerSideProps should be replaced by async components.

My problem is that I have a situation where I need to access the path in order to prefetch some data (I am loading metadata for the page from the server). Previously, I was using the NextApiRequest object that was passed as a parameter to the getServerSideProps function to retrieve the information about the path. I am unsure, however, how can I access this information in my async component.

I have tried to use the 'useRouter' hook to retrieve the path information, however hooks are not allowed on the Server components.


Solution

  • I think, new feature added at v 13.2 route-handlers

    A route.ts file can export an async function named by the HTTP verbs: GET, HEAD, OPTIONS, POST, PUT, DELETE, and PATCH. These functions can then be wrapped and abstracted to create helpers / reusable logic for your custom route logic.

    Other server functions, like cookies and headers, can be used inside Route Handlers – along with any Web APIs these abstractions are built upon. This allows for code to be shared between Server Components and Route Handlers.

    they also made an API change on Metadata as well. you can dynamically add metadata in each page file now. next-13-2