reactjsnext.jsserver-side-rendering

How to get query params using Server component (next 13)


Next13 is out, and they advise to use the new app directory where every component is by default a "Server Component"

Inside a "server Component", you can use:

But I can't find how to retrieve query params.

Before Next 13, within getServerSideProps, you could use context.query to access the query params.

Do you know how to retrieve query params using "server Component" in Next 13.


Solution

  • I don't think it's currently possible to do this in an arbitrary component. However, it is possible to access query parameters in page.tsx files, and pass these down to your components via props.

    export default function Page({
      params,
      searchParams,
    }: {
      params: { slug: string };
      searchParams?: { [key: string]: string | string[] | undefined };
    }) {
      return <h1>{searchParams?.greeting || "Hello!"}</h1>;
    }
    

    See the Docs