Server-side redirect
Answered
Expensiveee posted this in #help-forum
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()
24 Replies
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
export function GET(request) {
const id = request.nextUrl.searchParams.get("id");
if (!id) redirect("/");
redirect(`/${id}`);
}
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 ?
But about this, use the
searchParams
propYes but don’t use that
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
https://nextjs.org/docs/app/api-reference/functions/generate-metadata#generatemetadata-function
opengraph-image.tsx files probably support that as well
opengraph-image.tsx files probably support that as well
Let me see
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
Or maybe, I can have an API roujte that gens that pic, and use it in generateMetadata()
Answer
Yes, I was about to suggest this
That’s the best method in this case
Oh, rename it to route.tsx worked
Didn't know that was possible for API route
ðŸ‘