TanStackT
TanStack7mo ago
10 replies
radical-lime

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 } }) => {
        ...
    });


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 },
        ));
    ;
});


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 :).
Was this page helpful?