Redis in Node.js

Redis (Remote Dictionary Server) is an open-source, in-memory data structure store, used as a database, cache, and message broker. It supports various data structures such as strings, lists, sets, hashes, and more. Redis is known for its high performance, flexibility, and ease of use.

Setting Up Redis

Installation

To use Redis, you need to install it on your machine. Here’s a quick guide:

On Ubuntu:

				
					sudo apt update
sudo apt install redis-server

				
			

On macOS:

				
					brew install redis

				
			

Starting Redis Server:

				
					redis-server

				
			

Verify Installation:

				
					redis-cli ping
# Output: PONG

				
			

Installing Redis in Node.js

To use Redis in your Node.js application, you need to install the redis package.

Install Redis Package:

				
					npm install redis

				
			

Connecting to Redis Server

Create a file named redis-connection.js and add the following code:

				
					const redis = require('redis');

// Create a Redis client
const client = redis.createClient();

// Connect to Redis server
client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Handle connection errors
client.on('error', function(err) {
    console.log('Redis error: ' + err);
});

				
			

Output: When you run this script:

				
					node redis-connection.js

				
			

You should see:

				
					Connected to Redis...

				
			

Basic Redis Commands in Node.js

Let’s create a file named basic-commands.js to demonstrate basic Redis commands.

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Set a key
client.set('name', 'John', function(err, reply) {
    console.log(reply); // Output: OK
});

// Get a key
client.get('name', function(err, reply) {
    console.log(reply); // Output: John
});

// Increment a key
client.set('age', 25);
client.incr('age', function(err, reply) {
    console.log(reply); // Output: 26
});

// Delete a key
client.del('name', function(err, reply) {
    console.log(reply); // Output: 1
});

				
			

Working with Redis Data Types

Strings

Strings are the most basic kind of Redis value. They can contain any data type, including text, numbers, and binary data.

File: strings.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Setting a string
client.set('greeting', 'Hello, Redis!', function(err, reply) {
    console.log(reply); // Output: OK
});

// Getting a string
client.get('greeting', function(err, reply) {
    console.log(reply); // Output: Hello, Redis!
});

				
			

Lists

Lists are collections of ordered values. You can push values to the head or tail of the list.

File: lists.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Push values to a list
client.rpush(['tasks', 'Task 1', 'Task 2', 'Task 3'], function(err, reply) {
    console.log(reply); // Output: 3
});

// Retrieve values from a list
client.lrange('tasks', 0, -1, function(err, reply) {
    console.log(reply); // Output: [ 'Task 1', 'Task 2', 'Task 3' ]
});

				
			

Sets

Sets are collections of unique values.

File: sets.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Add values to a set
client.sadd(['tags', 'Node.js', 'Redis', 'Database'], function(err, reply) {
    console.log(reply); // Output: 3
});

// Get all values from a set
client.smembers('tags', function(err, reply) {
    console.log(reply); // Output: [ 'Node.js', 'Redis', 'Database' ]
});

				
			

Hashes

Hashes are collections of key-value pairs.

File: hashes.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Set values in a hash
client.hmset('user:1000', {
    'name': 'John',
    'age': '30',
    'email': 'john@example.com'
}, function(err, reply) {
    console.log(reply); // Output: OK
});

// Get values from a hash
client.hgetall('user:1000', function(err, reply) {
    console.log(reply);
    // Output: { name: 'John', age: '30', email: 'john@example.com' }
});

				
			

Sorted Sets

Sorted sets are similar to sets but have a score associated with each value.

File: sorted-sets.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Add values to a sorted set
client.zadd(['leaders', 1, 'John', 2, 'Doe', 3, 'Smith'], function(err, reply) {
    console.log(reply); // Output: 3
});

// Get values from a sorted set
client.zrange('leaders', 0, -1, 'WITHSCORES', function(err, reply) {
    console.log(reply); 
    // Output: [ 'John', '1', 'Doe', '2', 'Smith', '3' ]
});

				
			

Advanced Redis Features

Pub/Sub

Publish/Subscribe is a messaging pattern where senders (publishers) send messages to channels and receivers (subscribers) receive messages from channels.

File: pubsub.js

				
					const redis = require('redis');
const publisher = redis.createClient();
const subscriber = redis.createClient();

// Subscriber
subscriber.on('subscribe', function(channel, count) {
    console.log('Subscribed to ' + channel);
});
subscriber.on('message', function(channel, message) {
    console.log('Received message from ' + channel + ': ' + message);
});
subscriber.subscribe('notifications');

// Publisher
setTimeout(() => {
    publisher.publish('notifications', 'Hello, Subscribers!');
}, 1000);

				
			

Transactions

Redis supports transactions through the MULTI and EXEC commands.

File: transactions.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Start a transaction
client.multi()
    .set('user:1001', 'Alice')
    .set('user:1002', 'Bob')
    .exec(function(err, replies) {
        console.log(replies); // Output: [ 'OK', 'OK' ]
    });

				
			

Scripting

Redis supports Lua scripting.

File: scripting.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

const luaScript = `
    redis.call('SET', KEYS[1], ARGV[1])
    return redis.call('GET', KEYS[1])
`;

client.eval(luaScript, 1, 'foo', 'bar', function(err, reply) {
    console.log(reply); // Output: bar
});

				
			

Using Redis for Caching

Redis is commonly used for caching to improve application performance.

File: caching.js

				
					const redis = require('redis');
const client = redis.createClient();

client.on('connect', function() {
    console.log('Connected to Redis...');
});

// Cache middleware
const cache = (req, res, next) => {
    const { id } = req.params;
    client.get(id, (err, data) => {
        if (err) throw err;
        if (data !== null) {
            res.send(data);
        } else {
            next();
        }
    });
};

// Express app setup
const express = require('express');
const app = express();

app.get('/data/:id', cache, (req, res) => {
    const { id } = req.params;
    const data = { id, name: `Name${id}` };
    client.setex(id, 3600, JSON.stringify(data));
    res.send(data);
});

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

				
			

Redis in Production

When deploying Redis in a production environment, consider the following best practices:

  • Persistence: Enable AOF (Append Only File) for data durability.
  • Security: Use requirepass to set a password for your Redis server.
  • Scaling: Use Redis Cluster for horizontal scaling.
  • Monitoring: Use tools like Redis Sentinel for monitoring and automatic failover.

Practical example :User Data API with Redis Caching

let’s create a full practical example of a Node.js application that uses Redis for caching. We’ll build a simple Express.js API that fetches user data from a mock database and caches the results in Redis to improve performance.

Setting Up the Project

First, create a new directory for your project and initialize it with npm:

				
					mkdir user-data-api
cd user-data-api
npm init -y

				
			

Installing Dependencies

Install the necessary packages:

				
					npm install express redis

				
			

Creating the Mock Database

For this example, we’ll use a simple JSON object to represent our mock database. Create a file named database.js:

File: database.js

				
					const users = {
    1: { id: 1, name: 'John Doe', age: 30, email: 'john@example.com' },
    2: { id: 2, name: 'Jane Doe', age: 25, email: 'jane@example.com' },
    3: { id: 3, name: 'Jim Beam', age: 35, email: 'jim@example.com' }
};

module.exports = users;

				
			

Setting Up the Express Server

Create the main server file named server.js:

File: server.js

				
					const express = require('express');
const redis = require('redis');
const users = require('./database');

// Create a Redis client
const client = redis.createClient();

// Handle Redis connection errors
client.on('error', (err) => {
    console.log('Redis error: ' + err);
});

const app = express();
const PORT = 3000;

// Cache middleware
const cache = (req, res, next) => {
    const { id } = req.params;

    client.get(id, (err, data) => {
        if (err) throw err;

        if (data !== null) {
            res.send(JSON.parse(data));
        } else {
            next();
        }
    });
};

// Get user data
app.get('/user/:id', cache, (req, res) => {
    const { id } = req.params;
    const user = users[id];

    if (user) {
        client.setex(id, 3600, JSON.stringify(user));
        res.json(user);
    } else {
        res.status(404).json({ message: 'User not found' });
    }
});

app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

				
			

Running the Application

Start the Redis server if it’s not already running:

				
					redis-server

				
			

Run your Node.js application:

				
					node server.js

				
			

Testing the Application

You can test the API using a tool like curl or Postman. Here are some example curl commands:

Fetching User Data (First Time)

				
					curl http://localhost:3000/user/1

				
			

Output:

				
					{
    "id": 1,
    "name": "John Doe",
    "age": 30,
    "email": "john@example.com"
}

				
			

Fetching User Data (From Cache)

Subsequent requests for the same user will be served from the Redis cache:

				
					curl http://localhost:3000/user/1

				
			

Output (served from cache):

				
					{
    "id": 1,
    "name": "John Doe",
    "age": 30,
    "email": "john@example.com"
}

				
			

Dependencies:

  • express: A minimal and flexible Node.js web application framework.
  • redis: Node.js Redis client for interacting with the Redis server.

Mock Database (database.js):

  • Contains a simple JSON object representing user data.

Redis Client (server.js):

  • Created using redis.createClient().
  • Handles connection errors.

Cache Middleware:

  • Checks if the requested user data is present in the Redis cache.
  • If present, returns the cached data.
  • If not, proceeds to the next middleware/controller.

User Data Route (/user/:id):

  • Fetches user data from the mock database.
  • Stores the fetched data in Redis with a TTL (Time To Live) of 3600 seconds (1 hour).
  • Returns the user data in the response.

Redis is a powerful, versatile tool that can significantly enhance your Node.js applications by providing fast, in-memory data storage and retrieval. By leveraging its rich set of features, from basic commands to advanced functionalities like Pub/Sub and Lua scripting, you can build highly performant and scalable applications.Happy coding !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India