What's a good way to cache an API token for reuse? #4156
-
Using Vercel + Next.js with API routes where I need to pull data from an API that requires auth which returns a token that should be used until it expires, and then refresh it. Is there a way to cache this token so I don't need to also make the auth call on every request? This token needs to remain server side, to be used only by API routes so I can't cache it client side on the users cookie/local-storage/etc. Anyone faced the same issue? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Not an answer, but I can say I figured out you do not have ability to write to a file. I tried using node-persist. Maybe look for a similar package that keeps it in memory. |
Beta Was this translation helpful? Give feedback.
-
You could use a globally scoped variable in the API function like the following: let token = ''
module.exports = async (req, res) => {
if (!token) {
token = await generateToken()
}
const result = await fetchData(token)
res.send(result)
} If you need to persist the token longer, then I would recommend Redis which can assign a TTL. |
Beta Was this translation helpful? Give feedback.
You could use a globally scoped variable in the API function like the following:
If you need to persist the token longer, then I would recommend Redis which can assign a TTL.