React's cache in API Routes?
Unanswered
Simon Knittel 🍹 posted this in #help-forum
Hey!
Does [React's cache()](https://react.dev/reference/react/cache) also work in API Routes of Next.js 13/14?
I've got a route handler in which I call a function which is wrapped with
If it would be working, I would expect only one
Is that correct?
Does [React's cache()](https://react.dev/reference/react/cache) also work in API Routes of Next.js 13/14?
I've got a route handler in which I call a function which is wrapped with
cache(). To test this case I called that wrapped function multiple times right after another. I also added a console.log() inside that wrapped function.If it would be working, I would expect only one
console.log() entry. However, for each call to that wrapped function I'm a getting an individual console.log() entry. That indicates to me that the response of that wrapped function seems not to be getting cached.Is that correct?
7 Replies
American Crow
Not a cache expert. But I think React cache does not apply to API routes since they are not part of the component tree. Therefore Doesn't make sense to wrap them in react cache. Could be wrong though
Asian paper wasp
Note this statement from the doc
Since each route handler call is basically a new HTTP request, so no, it will not work the way you imagined it
React will invalidate the cache for all memoized functions for each server request.
Since each route handler call is basically a new HTTP request, so no, it will not work the way you imagined it
@Asian paper wasp Note this statement from the doc
> React will invalidate the cache for all memoized functions for each server request.
Since each route handler call is basically a new HTTP request, so no, it will not work the way you imagined it
I did not expect it to work across request. My test case is a single request:
export async function POST(request: Request) {
cachedFunction() // first call. logs as exepected
cachedFunction() // second call. also logs but I expected it won't
cachedFunction() // third call. also logs but I expected it won't
cachedFunction() // fourth call. also logs but I expected it won't
// ...
}@American Crow Not a cache expert. But I think React cache does not apply to API routes since they are not part of the component tree. Therefore Doesn't make sense to wrap them in react cache. Could be wrong though
Ok, that is disappointing. I will try to come up with something myself using AsyncLocalStorage
Asian paper wasp
If that's the case, then yeah I agree with @American Crow .
You can consider caches like LRU cache or TTL cahce though. Not sure which one fit's you more since I don't know your use case
You can consider caches like LRU cache or TTL cahce though. Not sure which one fit's you more since I don't know your use case
I kinda only need a request context which I can put some object in and reuse in other nested functions. All within a single request to my API / router handler.