33

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:

  • async/await to fetch data.
  • cookies() to retrieve cookies
  • headers() to retrieve request headers.

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.

Jonas
  • 121,568
  • 97
  • 310
  • 388
Tonio
  • 4,082
  • 4
  • 35
  • 60
  • I am not aware of any method to do that for now. I have been looking for a method as well but haven't gotten any luck. I only know of useSearchParams and that is for client-side components. Were you able to find a way and how did you do that? – Idris Dec 27 '22 at 14:42
  • I didn't find a solution for this so far – Tonio Dec 28 '22 at 15:09

3 Answers3

55

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

Kieran
  • 2,554
  • 3
  • 26
  • 38
8

I know this is going to sound bad but I have not found anything either, so you will have to parse it out yourself

here is an example

import type { NextRequest, NextResponse } from 'next/server';
import qs from 'qs';
export async function GET(request: NextRequest, response: NextResponse) {
   try {
      const rawParams = request.url.split('?')[1];
      const params = qs.parse(rawParams);
// Now you have access to the query String parameters //
// Or you can do it this way
      const yourParamName = request.nextUrl.searchParams.get('paramName');
// also try getAll() I think that might work
    } catch (error: unknown) {
      console.log(error);
   }
}
Peter the Russian
  • 1,170
  • 8
  • 9
  • 1
    In routes you can use `req.nextUrl.searchParams` which returns `URLSearchParams`. You get get a specific param by `req.nextUrl.searchParams.get("paramName")`. – Nishant May 16 '23 at 09:41
2

Finally, I found easy way get Query Value in next js 13.4

    const url = new URL(request.url);
    const searchParams = new URLSearchParams(url.search);
    const skip = searchParams.get("skip"); // Retrieves the value of the 'skip' parameter
    const limit = searchParams.get("limit"); // Retrieves the value of the 'limit' parameter

    console.log(skip);
    console.log(limit);