Next.js Discord

Discord Forum

how to access query params inside a server component ?

Answered
i_lost_to_loba_kreygasm posted this in #help-forum
Open in Discord
how to access query params inside a server component ?
Answered by B33fb0n3
you can access them by accessing their param like:
export default function Page({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  return <h1>My Page with search query: {(await searchParams).query}</h1>
// .query is just an example for the matching url of https://.../?query=hello
}

Depending on which version of nextjs you using it's either a promise or already awaited.
# next15:
export default async function Page({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  const filters = (await searchParams).filters
}

# next14:
export default function Page({
  params,
  searchParams,
}: {
  params: { slug: string }
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  return <h1>My Page</h1>
}
View full answer

12 Replies

@B33fb0n3 hi 🙂
Burmese
But I am using App router
@i_lost_to_loba_kreygasm how to access query params inside a server component ?
you can access them by accessing their param like:
export default function Page({
  params,
  searchParams,
}: {
  params: Promise<{ slug: string }>
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  return <h1>My Page with search query: {(await searchParams).query}</h1>
// .query is just an example for the matching url of https://.../?query=hello
}

Depending on which version of nextjs you using it's either a promise or already awaited.
# next15:
export default async function Page({
  searchParams,
}: {
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>
}) {
  const filters = (await searchParams).filters
}

# next14:
export default function Page({
  params,
  searchParams,
}: {
  params: { slug: string }
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  return <h1>My Page</h1>
}
Answer
I got it
Burmese
That was the wrong link I sent. My bad.
its solved , the params is an empty object for some reason
probably the latest
@i_lost_to_loba_kreygasm probably the latest
then you probably using next15. Keep in mind to await your searchParams (see attached).

Also make sure your url contains searchParams.
https://example.com/hello/world -> no searchParams available
https://example.com/hello/world?search=someValue -> the searchParam search is available
yeah I awaited it for safety , you can mark it as solved now , thanks for the help 🙂
happy to help

You are welcome to ping me in your next threads as well 🙂