CodexBloom - Programming Q&A Platform

Issues with Caching HTTP Responses in Node.js Express App Using Redis

👀 Views: 67 💬 Answers: 1 📅 Created: 2025-07-22
node.js express redis caching JavaScript

I'm working on a Node.js application using Express and I'm trying to implement caching for my API responses using Redis. However, I'm encountering an issue where my cached responses are not being served correctly. I've installed the `redis` and `connect-redis` packages and I'm using `express-session` for session management. My goal is to cache responses from a specific route for a duration of 10 minutes to reduce load on my database. Here’s how I'm setting up my Redis client: ```javascript const session = require('express-session'); const RedisStore = require('connect-redis')(session); const redis = require('redis'); const redisClient = redis.createClient({ host: '127.0.0.1', port: 6379, }); app.use(session({ store: new RedisStore({ client: redisClient }), secret: 'mySecret', resave: false, saveUninitialized: false, cookie: { secure: false }, // Set to true if using https })); ``` In my route, I’m trying to cache the response like this: ```javascript app.get('/api/data', async (req, res) => { const cacheKey = 'dataCache'; redisClient.get(cacheKey, async (err, cachedData) => { if (cachedData) { return res.json(JSON.parse(cachedData)); } const data = await fetchDataFromDatabase(); // Hypothetical function to fetch data redisClient.setex(cacheKey, 600, JSON.stringify(data)); // Cache for 10 minutes return res.json(data); }); }); ``` I’ve verified that the Redis server is running and I can connect to it from my Node.js app. However, I’m noticing that every time I hit the `/api/data` route, it’s making a new request to the database instead of serving the cached response. I’ve also checked the Redis database, and the `dataCache` key is not being created at all. I've tried adding error handling for the Redis client and ensuring that the `fetchDataFromDatabase` function is returning data correctly, but I still see no cached responses. I’ve logged the errors and responses, and there don’t seem to be any exceptions thrown. Is there something I’m missing in the setup? Any insights on how I can properly implement caching with Redis in this scenario?