An introduction to Caching with Redis in Node.js application

An introduction to Caching with Redis in Node.js application

Caching is the process of storing data into a cache. In this article, We will discuss caching with Redis in Node.js application.

A cache is a temporary data store where data is kept for later use. It is not a good approach if we go to database and query for the same data every time. So in this scenerio, we save the data in cache for the first time and retrieve data from cache inplace of database. It increases the app performance a lot.

For a web developer, it's very necessary to increase the performance and make the app respond faster, And for achieving this we use caching at the server end.

What is Redis?

Official doc says - Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

Let's Get Started

Step 1: Install Redis over local machine

At first, Install *Redis *over local system with below command over *ubuntu *system.

sudo apt-get install redis-server

Step 2: Create Node.js application

Create a project folder, redis-nodejs, move to the folder over terminal and create a nodejs app with default package.json file with below command over terminal.

npm init --yes

Step 3: Install required packages

Now install express, redis, node-fetch npm packages with below command:

npm i express node-fetch redis 

Step 4: update server.js file

create a file, server.js inside project folder and put the below code inside this file:

const express = require('express');
const app = express() // create express app

const fetch = require("node-fetch");
const redis = require('redis');



const client = redis.createClient(6379); //connect redis client with local instance.

// echo redis errors to the console
client.on('error', (err) => {
console.log("Error " + err)
});

// get user list
app.get('/user-list', (req, res) => {
const todoRedisKey = 'user:userList';
// Try fetching the result from Redis first in case we have it cached
return client.get(todoRedisKey, (err, users) => {

// If that key exists in Redis store
if (users) {
console.log('fetching data from cache-----');
return res.json({ source: 'cache', data: JSON.parse(users) })

} else { // Key does not exist in Redis store
console.log('fetching data from api-----');
// Fetch directly from remote api
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(users => {

// Save the API response in Redis store, data expire time in 3600 seconds, it means one hour
client.setex(todoRedisKey, 3600, JSON.stringify(users))

// Send JSON response to client
return res.json({ source: 'api', data: users })

})
.catch(error => {
// log error message
console.log(error)
// send error to the client
return res.json(error.toString())
})
}
});
});

// start express server at 3000 port
app.listen(3000, () => {
console.log('Server listening on port: ', 3000)
});

Step 5: Run the Node.js application

Type below command over terminal in project folder.

node  server.js

Now go to the browser at and

Enter url: http://localhost:3000/user-list in the url. When yo will fetch the data for the first time, then data will come after calling the api and from the next request, data will fetch from the cache only. And if request time of first request 4000 ms then from the next it will take around 1000 ms.

Conclusion

*Redis *is very powerful in-memory data-store that we can use in our applications. It’s very simple to save and get data without much overhead.

So in this article, We understand the implementation of Redis *in *Node.js application with a very basic example

node-js redis web-development

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Node JS Developer from Expert Node JS Development Company

NodeJS Development Company-Hire Node JS developer from the most prominent NodeJS development company, Mobiweb and get remarkable Node.js app development services.

Main Reasons of Using Node JS for Your Web Application Development

You have to hire Node JS developer from prestigious and expert Node JS development company Mobiweb Technologies. They are tech enthusiasts with new and latest programming ideas, web development technologies and industry trends.

How to Hire Node JS Developers and How Much Does It Cost.

The developer community has witnessed the boom of Node.js in the past years. The year 2017 brought Node JS in limelight with the number of projects being developed in Node.JS. The high demand and the immense scope of development withdrew...