Next.js Discord

Discord Forum

Best practice for conditional cacheLife() with "use cache" in Next.js 15

Unanswered
Snowshoe posted this in #help-forum
Open in Discord
SnowshoeOP
I'm using the new "use cache" directive in Next.js 15 along with cacheLife(). I want to set a longer cache duration (e.g. 1 hour) when an API call succeeds, but a much shorter cache duration (e.g. seconds or none) when the API fails. Also, instead of throwing an error, I want to return a friendly error object.

However, I know cacheLife() must be called synchronously — so I can’t put it inside a try/catch meaning i can not condicionally wait for the status of the api call. What’s the recommended pattern for this? Should I split the logic into multiple functions or is there a better way to handle conditional caching based on success/failure?

0 Replies