How to pass URL parameter to Sanity GROQ query in Next.js getServerSideProps?
4 replies
Last updated: Aug 6, 2022
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:
- In
getServerSideProps, you get the URL parameters from thecontext.queryobject (notrouter.query- that's for client-side components) - Pass your parameters as an object in the second argument to
sanityClient.fetch() - In your GROQ query, reference the parameter with the
$prefix
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 thread4 replies
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.