How to Use Redis Cache in Express for Fast Data Access
To use
redis cache in express, install the redis client and connect it to your Redis server. Then, use Redis commands like get and set inside your Express routes to store and retrieve cached data, improving response speed.Syntax
Here is the basic syntax to connect Redis with Express and use caching:
import redis from 'redis': Import Redis client.const client = redis.createClient(): Create Redis client instance.await client.connect(): Connect to Redis server.client.get(key): Retrieve cached value by key.client.set(key, value, options): Store value with key and optional expiry.
javascript
import express from 'express' import redis from 'redis' const app = express() const client = redis.createClient() await client.connect() app.get('/data', async (req, res) => { const cacheKey = 'myData' const cachedData = await client.get(cacheKey) if (cachedData) { return res.send({ source: 'cache', data: JSON.parse(cachedData) }) } const data = { message: 'Hello from server' } // Simulate data fetch await client.set(cacheKey, JSON.stringify(data), { EX: 60 }) // Cache for 60 seconds res.send({ source: 'server', data }) })
Example
This example shows a simple Express server using Redis to cache a JSON response for 60 seconds. If the data is cached, it returns the cached version; otherwise, it fetches fresh data and caches it.
javascript
import express from 'express' import redis from 'redis' const app = express() const client = redis.createClient() client.on('error', (err) => console.log('Redis Client Error', err)) async function start() { await client.connect() app.get('/data', async (req, res) => { const cacheKey = 'myData' const cachedData = await client.get(cacheKey) if (cachedData) { return res.json({ source: 'cache', data: JSON.parse(cachedData) }) } // Simulate slow data fetch const data = { message: 'Hello from server', time: new Date().toISOString() } await client.set(cacheKey, JSON.stringify(data), { EX: 60 }) res.json({ source: 'server', data }) }) app.listen(3000, () => console.log('Server running on http://localhost:3000')) } start()
Output
Server running on http://localhost:3000
// When you visit http://localhost:3000/data
// First request output:
// { source: 'server', data: { message: 'Hello from server', time: '2024-06-01T12:00:00.000Z' } }
// Subsequent requests within 60 seconds:
// { source: 'cache', data: { message: 'Hello from server', time: '2024-06-01T12:00:00.000Z' } }
Common Pitfalls
Common mistakes when using Redis cache in Express include:
- Not awaiting
client.connect()before using Redis commands, causing errors. - Forgetting to JSON.stringify data before caching complex objects.
- Not setting an expiration time, leading to stale cache.
- Not handling Redis connection errors, which can crash the app.
javascript
/* Wrong way: Missing await on connect and no JSON stringify */ import redis from 'redis' const client = redis.createClient() await client.connect() // Added await here app.get('/data', async (req, res) => { const cached = await client.get('key') if (cached) return res.send(cached) // returns string, not parsed const data = { hello: 'world' } await client.set('key', JSON.stringify(data)) // data stringified res.send(data) }) /* Right way: */ await client.connect() app.get('/data', async (req, res) => { const cached = await client.get('key') if (cached) return res.json(JSON.parse(cached)) const data = { hello: 'world' } await client.set('key', JSON.stringify(data), { EX: 60 }) res.json(data) })
Quick Reference
Key Redis commands for Express caching:
| Command | Description |
|---|---|
| client.connect() | Connects to Redis server asynchronously |
| client.get(key) | Retrieves cached value by key, returns string or null |
| client.set(key, value, { EX: seconds }) | Stores value with expiration time in seconds |
| client.del(key) | Deletes cached key |
| client.quit() | Closes Redis connection |
Key Takeaways
Always await client.connect() before using Redis commands in Express.
Cache JSON data by stringifying before storing and parsing after retrieval.
Set expiration times to avoid stale cache data.
Handle Redis connection errors to keep your Express app stable.
Use Redis cache to speed up repeated data requests in Express routes.