T
TanStack•2mo ago
sunny-green

Caching server Functions?

Hello, To cache some server functions in my tanstack Start app I do this: the server function:
export const getPlatformStats = createServerFn({ method: "GET" })
.middleware([authMiddleware, platformStatsCacheMiddleware])
.validator(data => plaftformStatsSchema.parse(data))
.handler(async ({ data: { mediaType } }) => {
...
});
export const getPlatformStats = createServerFn({ method: "GET" })
.middleware([authMiddleware, platformStatsCacheMiddleware])
.validator(data => plaftformStatsSchema.parse(data))
.handler(async ({ data: { mediaType } }) => {
...
});
the cache middleware:
export const platformStatsCacheMiddleware = createMiddleware({ type: "function" }).server(async ({ next, data }) => {
const cacheKey = `platformStats:${JSON.stringify(data ?? null)}`;

// Cached for 24 hours
return getContainer()
.then(c => c.cacheManager.wrap(
cacheKey,
async () => next(),
{ ttl: 24 * 60 * 60 * 1000 },
));
;
});
export const platformStatsCacheMiddleware = createMiddleware({ type: "function" }).server(async ({ next, data }) => {
const cacheKey = `platformStats:${JSON.stringify(data ?? null)}`;

// Cached for 24 hours
return getContainer()
.then(c => c.cacheManager.wrap(
cacheKey,
async () => next(),
{ ttl: 24 * 60 * 60 * 1000 },
));
;
});
I'm using the npm package cache-manager under the hood, which is either initialized using Redis in prod or in memory otherwise. Is this ok ? Thanks in advance :).
3 Replies
helpful-purple
helpful-purple•2mo ago
why shouldnt it be okay?
sunny-green
sunny-greenOP•2mo ago
just asking to be sure 🙂
helpful-purple
helpful-purple•2mo ago
it looks good to me it could probably be generalized a bit so you could cache arbitrary functions

Did you find this page helpful?