Next.js Discord

Discord Forum

Cache a dynamic route handler

Answered
Florian posted this in #help-forum
Open in Discord
Does Next.js have a mechanism to cache this dynamic route.ts file? Or do I need to build my own caching mechanism (e.g. Redis)?

If this was a page.tsx, I could export generateStaticParams and it would cache each dynamic route after the first access. Can I achieve the same in route.ts?

export async function GET(
  req: Request,
  { params: { url } }: { params: { url: string } },
) {
  try {
    const ogResult = await ogScrape({ url });

    if (ogResult.error) {
      console.error(ogResult.result.error);
      throw new Error("Failed to scrape og data");
    }

    const responseBody: OgData = {
      link: url,
      title: ogResult.result.ogTitle,
      description: ogResult.result.ogDescription,
      image: ogResult.result.ogImage?.[0].url,
    };

    return Response.json(responseBody);
  } catch (error) {
    console.error(error);
    return Response.json({ error: "Internal server error" }, { status: 500 });
  }
}
Answered by ᴉuɐpɹɐɐ
you can just return [] lol
View full answer

17 Replies

That sounds like it could work 😎 Thank you I'll try it out.
that's so cool
So what I do is, I just return a placeholder URL. The other ones will be cached at first acccess. Does this make sense?

export function generateStaticParams() {
  return [{ url: "https://example.com" }];
}
you can just return [] lol
Answer
thats how straightforward the ISR feature is
Ah, thank you
Do you know if unstable_cache gets cleared then the project is rebuilt/redeployed?
no
they dont
but they have a limit now, not that its pricey but if you go over the limit, the old cache would just get thrown away, and youd probably need to call ogScrape again
Interesting, thank you. Then maybe unstable_cache is still a better solution to avoid clearing the whole cache on every rebuild.
i honestly havent tried it but theorhetically you'd get best of both worlds haha
Yea that could make sense