Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials Node.js Redis Caching
Node.js Intermediate FREE

Redis Caching

Lesson 1 of 17 Intermediate Interactive

Redis is an in-memory data store used for caching, sessions, and real-time data.

Syntax

NODEJS
const Redis = require('ioredis');
const redis = new Redis();

await redis.set('key', 'value', 'EX', 3600);
const value = await redis.get('key');
Redis Caching
NODE
const redis = require("redis");
const client = redis.createClient();

async function cacheData(key, data, ttl = 3600) {
    await client.setEx(key, ttl, JSON.stringify(data));
}

async function getCachedData(key) {
    const data = await client.get(key);
    return data ? JSON.parse(data) : null;
}

async function getUser(userId) {
    const cached = await getCachedData(`user:${userId}`);
    if (cached) return cached;

    const user = await db.findUser(userId);
    await cacheData(`user:${userId}`, user);
    return user;
}