Next.js Discord

Discord Forum

Question about unstable_cache

Unanswered
Palomino posted this in #help-forum
Open in Discord
PalominoOP
is this the right way to do this or do i still have to pass the sanitize as cache key to handle some edge cases that I can't think of right now?
export const getCachedProduct = (
    slug: string,
    sanitize: boolean
) => {
    return unstable_cache(
        async () => {
            const product = await prisma.product.findUnique({
                where: { slug },
                select: {
                    id: true,
                    name: true,
                    description: true,
                    price: true,
                    imageUrl: true,
                    secretInfo: true,
                },
            });

            const result = product ? structuredClone(product) : null;

            if (result && sanitize) {
                result.secretInfo = null;
            }

            return result;
        },
        [slug],
        {
            tags: [`product-${slug}`],
        }
    )();
};

9 Replies

PalominoOP
yeah it's all done on the server
i use sanitize whn im gonna pass the product to the client side eventually
i cloned it because for some reason when i asked claude about this he kept screaming at me telling me im gonna mutate the origina nextjs cache which seems a bit weird
is it just hallucinating ?
yea, you only mutate the cache, with whatever you return inside the function. It doesnt matter if its a cloned object or just the normal object
PalominoOP
so the cloning is pointless here
and there's also no need to pass sanitize as cache key
@Palomino so the cloning is pointless here and there's also no need to pass sanitize as cache key
cloning seems for me pointless here, yea. The cache is shared with other users. IMO I would never cache secret data that is shared with others as they might leak
PalominoOP
yeah but how's it going to leak? that's what the sanitize arg is for
whenever im planning to pass that data to the client side then i set sanitize to true
is that still insecure somehow?
imagine you somewhen dont set the sanitize value. For example because you want to work serverside with the fetched product or whatever (cache MISS + SET). And then you request the same method to fetch a product and display it (for example on the products page) for the user (cache HIT). Now the server leaked data even if you set sanitize to false