Next.js Discord

Discord Forum

App route handler - persisting data between requests?

Unanswered
Himalayan posted this in #help-forum
Open in Discord
HimalayanOP
I have an API route handler defined (route.ts), it's essentially a proxy to an external service, but part of what it does is obtain an access key. I want to cache this key so subsequent requests don't have to go through the process of obtaining it until it expires.

What's the "proper" way of persisting this in a route handler? Many thanks!

10 Replies

Milkfish
Easiest way is to probably use the data cache
cache the entire response, and set a revalidate token to the length the key is valid for
@Milkfish Easiest way is to probably use the data cache
HimalayanOP
Oooh, that sounds promising, I've not come across the data cache before, I'll do some investigating. Thanks @Milkfish 🙂
Milkfish
no worries
the thing with using a variable is just that you may see one authentication per deployment of your route handler and per route handler
because of the serverless nature of Next
unstable_cache is still unstable so not sure about the exact spec but it might be a tad more powerful, like allowing to cache across different routes
you can also store the API key in your db if that makes sense, then it would be shared by all your routes
@Eric Burel the thing with using a variable is just that you may see one authentication per deployment of your route handler and per route handler
HimalayanOP
Thanks @Eric Burel Fortunately it's likely to only be this one route that will require this cached key so that simplifies things. I'll look into unstable_cache 👍