Jalan Technologies > Blog >

How to cache with Redis in Nodejs | Simple steps

Implementing caching with Redis in Node.js can significantly boost the speed and efficiency of web applications by reducing the need for frequent server-side operations. Redis, an in-memory data store, stores data as key-value pairs, making it incredibly fast. Learn how to set up Redis caching in Node.js to enhance your application's performance.

The process where you store data in a temporary location with the purpose of accessing it with little resources is caching. In web applications, caching is widely used for decreasing the bandwidth and making applications fast especially when we are concerned with expensive operations on the server-side. In this article, we will see how you can implement caching with Redis in Nodejs through a simple example.

Cache with Redis in Nodejs

Before getting started, let us see what is Redis?

Redis

Redis is an open-source in-memory storage store that works as a database, cache, and message broker. Redis stores data in the form of key-value pairs inside the system’s memory which makes it extremely fast.

Using Redis with Nodejs.

We will be going through a straightforward implementation where we will see if the user request data is present on the route where we have caching enabled. If we find the appropriate data that fulfills the request, we return a response from the cache. Otherwise, we hit the external API or database to return the response while storing the data retrieved.

Before you start writing code, make sure you have nodejs, and redis installed in your local machine. Then set up the project with the following command.

npm init

The next step is to install all the dependencies that we are going to use in our project. Use the command below:

npm install axios express redis nodemon

Create a file named server.js and enter the following code to set the boilerplate for our project.

Server.js

const express = require("express");
const axios = require("axios");
const redis = require("redis");
const app = express();
 
app.listen(process.env.PORT || 3000, () => {
   console.log("Node server started");
});

We will use jsonplaceholder API in our project for implementing caching. Let us add the following route to our express server.

app.get('/:searchtext', async(req, res) => {
   const searchtext = req.params.searchtext;
    const recipe = await axios.get(`https://jsonplaceholder.typicode.com/${searchtext}`);
     return res.status(200).send({
           error: false,
           message: `Data for ${searchtext} from the server`,
           data: recipe.data
         });
   })

A request to this route in postman will look as follows.

 

Redis in Nodejs

 

If we make another request, we see the result as follows.

 

Cache in Nodejs

 

We can see that the information has not changed but still there is same amount of time that is being taken to get the data.

We will improve this time by storing the response in our redis cache. Our server.js will have the following final code with Redis caching implemented.

const express = require('express');
const axios = require('axios');
const redis = require('redis');
const app = express();
const port = 4000;
const client = redis.createClient(6379);
client.on("error", (error) => {
console.error(error);
});
app.get('/:searchtext', (req, res) => {
try {
  const searchtext = req.params.searchtext;
  client.get(searchtext, async (err, data) => {
    if (data) {
       return res.status(200).send({
        error: false,
        message: `Data for ${searchtext} from the cache`,
        data: JSON.parse(data)
      })
    } else {
        const recipe = await axios.get(`https://jsonplaceholder.typicode.com/${searchtext}`);
        client.setex(searchtext, 1020, JSON.stringify(recipe.data));
        return res.status(200).send({
          error: false,
          message: `Data for ${searchtext} from the server`,
          data: recipe.data
        });
    }
  })
} catch (error) {
    console.log(error)
}
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});

Lets us explore what is happening here. He have intialized the redis client on its default port. Inside our route, the client gets the key and checks the data against it in the memory cache. If we find the data against the specified keyvalue pair, we simply return it in the response and if there is no data against the specified keyvalue pair, we fetch the required data from our API.

Client.setex() is the main function that takes a key and sets the data against it. It also takes time to specifiy the validity of the cache. Now, let us hit our API in postman and see the time taken by subsequent requests.

1st request

 

Redis

 

2nd request

Nodejs

 

If you notice the response time, there is a huge difference from before. This is all because of in-memory caching by Redis.

Conclusion

In this article, we have seen how to implement cache with Redis in nodejs. This tutorial used a basic implementation that would be great to get started with Redis and in-memory caching. You can always explore and learn more about it.

Are you facing a technological puzzle that’s been keeping you up at night? At Jalan Technologies, we’re here to unravel it for you! Contact us today, and let’s tackle your most challenging tech issues together. We’re here to make technology work seamlessly for your business.

Disclaimer: The statements and opinions expressed in this article are those of the author(s) and do not necessarily reflect the positions of Jalan Technologies.

Table of Contents

Hire Our Development Experts.




    Want to raise the bar for your organization?

    Subscribe to our newsletter to receive latest insights on how technology can help turn your goals into reality. By subscribing, you’ll get access to thought-provoking articles, case studies, and resources to help accelerate your impact.

    Get the latest updates straight to your inbox

      Related Blogs
      technology consultant
      Business Insights
      All you need to know about technology consultant

      Technology consultant experts like Jalan Technologies, empowers businesses to strategically leverage technology for success. Services encompass strategic planning, system integration,

      Scroll to Top

      Subscribe Now

        Never Miss Another Post