Sanity Pioneers: Get early access to betas, extra AI credits, and a direct line to the engineering team. Apply now

How to pass URL parameter to Sanity GROQ query in Next.js getServerSideProps?

4 repliesLast updated: Nov 29, 2025

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.
AI Update

You're really close! The key is to pass the parameters as the second argument to the fetch() method. Here's how to fix your code:

export const getServerSideProps = async ({ query }) => {
  const { orderId } = query
  
  const orderDetails = await sanityClient.fetch(
    `*[_type == "orders" && orderId.current == $orderId][0]{...}`,
    { orderId } // Pass parameters as second argument
  )
  
  return {
    props: {
      orderDetails,
    },
  }
}

The important bits:

This approach is much safer than string interpolation because the Sanity client automatically handles proper escaping, preventing GROQ injection attacks and syntax errors from special characters.

If you need to handle cases where orderId might not be present in the URL, you can add a check:

export const getServerSideProps = async ({ query }) => {
  const { orderId } = query
  
  if (!orderId) {
    return { notFound: true }
  }
  
  const orderDetails = await sanityClient.fetch(
    `*[_type == "orders" && orderId.current == $orderId][0]{...}`,
    { orderId }
  )
  
  return {
    props: {
      orderDetails,
    },
  }
}
Show original thread
4 replies

Was this answer helpful?

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Related contributions