Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to Set Params for a Query From a URL Parameter

4 replies
Last updated: Aug 6, 2022
Hey everyone. Quick question, how can I set params for a query from a URL parameter? Say I have this url:
orders?orderId=778
and I want to fetch the order 778 from Sanity:
export const getServerSideProps = async () => {
  const orderDetails = await sanityClient.fetch(
    `*[_type == "orders" && orderId.current == $orderId][0]{...}`
  )
  return {
    props: {
      orderDetails,
    },
  }
}
I know I can use
router.query
in Next.js so
const { orderId } = router.query
will read the URL param, but I can’t seem to be able to pass it as params to the groq query.
Aug 5, 2022, 11:41 PM
Parameters are the second argument to
fetch()
, so:
sanityClient.fetch(
  `*[_type == "orders" && orderId.current == $orderId][0]{...}`,
  {orderId: router.query.orderId}
)
Aug 6, 2022, 2:44 AM
Hi
user Z
, thanks! I think I already try that but it'll check again. I remember getting an error about using hook calls within
getServerSideProps
Aug 6, 2022, 2:53 AM
Yeah, you need to pick
query
from the context argument
getServerSideProps
gets - something like:

export const getServerSideProps = async (context) => {
  const orderDetails = await sanityClient.fetch(
    `*[_type == "orders" && orderId.current == $orderId][0]{...}`,
    {orderId: context.query.orderId}
  )
  return {
    props: {
      orderDetails,
    },
  }
}
Aug 6, 2022, 2:56 AM
Ahhh, the context! I keep forgetting about it. It works now, thank you!
Aug 6, 2022, 1:48 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?