0
0
Expressframework~5 mins

Redis integration for distributed cache in Express

Choose your learning style9 modes available
Introduction

Redis helps store data temporarily so many servers can share it fast. This makes apps quicker and smoother.

You want to save user session info so users stay logged in across servers.
You need to store temporary data like shopping cart items shared by many servers.
You want to reduce slow database calls by caching frequent data.
You run an app on many servers and want them to share the same fast data.
You want to handle sudden traffic spikes without slowing down your app.
Syntax
Express
import express from 'express';
import { createClient } from 'redis';

const app = express();
const redisClient = createClient();

redisClient.on('error', (err) => console.log('Redis Client Error', err));

(async () => {
  await redisClient.connect();

  app.get('/cache', async (req, res) => {
    const key = 'someKey';
    let value = await redisClient.get(key);
    if (!value) {
      value = 'some expensive data';
      await redisClient.set(key, value, { EX: 60 }); // expires in 60 seconds
    }
    res.send(value);
  });

  app.listen(3000);
})();

Use createClient() from the official Redis package to connect.

Use async/await because Redis calls are asynchronous.

Examples
Store user data as a string with a 5-minute expiration.
Express
await redisClient.set('user:123', JSON.stringify({ name: 'Alice' }), { EX: 300 });
Retrieve and convert the stored string back to an object.
Express
const data = await redisClient.get('user:123');
const user = JSON.parse(data);
Remove a cached item when no longer needed.
Express
await redisClient.del('user:123');
Sample Program

This Express app counts how many times the /visit page is loaded using Redis as a shared counter. Each visit increases the count stored in Redis and shows it.

Express
import express from 'express';
import { createClient } from 'redis';

const app = express();
const redisClient = createClient();

redisClient.on('error', (err) => console.log('Redis Client Error', err));

(async () => {
  await redisClient.connect();

  app.get('/visit', async (req, res) => {
    const visits = await redisClient.get('visits');
    const newVisits = visits ? parseInt(visits) + 1 : 1;
    await redisClient.set('visits', newVisits.toString());
    res.send(`Number of visits: ${newVisits}`);
  });

  app.listen(3000, () => console.log('Server running on port 3000'));
})();
OutputSuccess
Important Notes

Always handle Redis connection errors to avoid app crashes.

Set expiration times on cached data to keep cache fresh.

Use JSON.stringify and JSON.parse to store complex data structures.

Summary

Redis stores data fast and shared across servers for better app speed.

Use Redis in Express with async calls and proper error handling.

Cache data with expiration to keep it updated and save resources.