Server-side caching — stores frequently accessed data in fast storage.
Using NodeCache (in-memory):
1const NodeCache = require("node-cache");2const cache = new NodeCache({ stdTTL: 300 }); // 5 min34app.get("/users/:id", async (req, res) => {5 const key = `user_${req.params.id}`;6 let user = cache.get(key);78 if (!user) {9 user = await db.getUser(req.params.id);10 cache.set(key, user);11 }1213 res.json(user);14});
Using Redis (distributed):
1const redis = require("redis").createClient();23async function getCached(key, fetchFn, ttl = 300) {4 let data = await redis.get(key);5 if (data) return JSON.parse(data);67 data = await fetchFn();8 await redis.setEx(key, ttl, JSON.stringify(data));9 return data;10}1112// Usage13app.get("/products", async (req, res) => {14 const products = await getCached("products", () => db.getProducts());15 res.json(products);16});
Cache strategies: