Next.js Discord

Discord Forum

Server-side redirect

Answered
Expensiveee posted this in #help-forum
Open in Discord
Avatar
Hello, I'm looking to have a page/route for example /aaa?id=123 that redirects from the server to /123, I can't seem to do it without rendering some HTML which I don't want.
Answered by Expensiveee
Or maybe, I can have an API roujte that gens that pic, and use it in generateMetadata()
View full answer

24 Replies

Avatar
The reason I want this is that I receive an url in this format /aaa?id=MY_ID and I need to redirect to/MY_ID to be able to retreive that id and use this param to generate a metadata image. I can't access searchParams server side
Avatar
export function GET(request) {
  const id = request.nextUrl.searchParams.get("id");
  if (!id) redirect("/");
  redirect(`/${id}`);
}
Avatar
And redirecting through the server, will allow discord/twitter/facebook etc to get redirect to that page which will have the right metadata image and not first got to /aaa and get THAT metadata img, but rather get rerouted directly
Would this work even if not in /api ?
Avatar
But about this, use the searchParams prop
Yes but don’t use that
Avatar
Can I access it in a opengraph-image.tsx file?
// Image generation
export default async function Image({ params }: { params: { id: string } }) {
  const transaction = await getTransaction(params.id).catch((e) =>
    console.log("ERROR", e)
  );

  console.log("TRANSACTION IS", transaction);

  if (!transaction) {
    return new ImageResponse(
      (

// Making my image in html/css
....
that under /[id]/opengraph-image.tsx
Which allows me to access that ID, since I can't get it though searchParams
Idk if I'm clear
So like first it goes through this
Image
Avatar
Avatar
Let me see
Avatar
This doesn't really work:
// Image generation
export default async function Image({ searchParams }: { searchParams: any }) {
  console.log(searchParams);

  return new ImageResponse(<h1>Hello</h1>);
}
Because the actual searchParam comes form the page.tsx, which opengraph-image.tsx doesn't have access to I think
Avatar
Or maybe, I can have an API roujte that gens that pic, and use it in generateMetadata()
Answer
Avatar
Yes, I was about to suggest this
That’s the best method in this case
Avatar
But then, how would I write jsx in a route.tsx
Image
Oh, rename it to route.tsx worked
Didn't know that was possible for API route
👍