Next.js Discord

Discord Forum

Accessing Search Params in opengraph-image.ts

Unanswered
Orinoco Crocodile posted this in #help-forum
Open in Discord
Avatar
Orinoco CrocodileOP
Hey 👋,
Is there a way to access the search params in the opengraph-image generation function? Couldn't find anything about that in the docs

4 Replies

Avatar
What opengraph-image function? The ImageResponse in next/og? Your functions are up to you and whatever you write.

If you write an API route GET endpoint, just get the searchParams from the nextUrl in the NextRequest coming in. I saw a guy share his GitHub project to generate images from URL Parameters, and I've since am working on a similar tool but with POST Requests and returning an ArrayBuffer. Here's the other guys repository where you can see his API here and how he pulls the searchParams: https://github.com/AsaoluElijah/url-images/blob/main/pages/api/cover.js
Avatar
Orinoco CrocodileOP
Thanks for your responses.
I'm currently using the opengraph-image specialized route hander https://nextjs.org/docs/app/api-reference/file-conventions/metadata/opengraph-image#generate-images-using-code-js-ts-tsx
Not quite sure if I understand what you are trying to say, should I just create a "normal" route and set the opengraph image url manually?
Avatar
The repository's code I shared does exactly what I believe you're trying to accomplish but with Pages router and older NextJS 13, the idea is the same though. If you plan on using it in the examples sense of a <meta> tag, then they wouldn't be searchParams and would be properties passed to the child component opengraph-image.tsx in the nextjs.org example.

To create it an API Route you can pring with a GET Request and return the result, do this:

export async function GET(request: NextRequest) {
  const searchParams = useSearchParams()
  const size = searchParams.get('size')

  return new ImageResponse(
    //Image here
  )
}