<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Saar Amrani</title>
    <description>The latest articles on DEV Community by Saar Amrani (@saar120).</description>
    <link>https://dev.to/saar120</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F853367%2Fe8040184-00aa-417c-bde2-a1764a7d8bcc.jpeg</url>
      <title>DEV Community: Saar Amrani</title>
      <link>https://dev.to/saar120</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/saar120"/>
    <language>en</language>
    <item>
      <title>Implement caching in Node.js with Redis</title>
      <dc:creator>Saar Amrani</dc:creator>
      <pubDate>Mon, 25 Apr 2022 21:32:54 +0000</pubDate>
      <link>https://dev.to/saar120/implement-caching-in-nodejs-with-redis-4b7o</link>
      <guid>https://dev.to/saar120/implement-caching-in-nodejs-with-redis-4b7o</guid>
      <description>&lt;p&gt;Caching is a simple mechanism that can make your API respond faster to a request that is repetitive.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Let's describe our problem:&lt;/strong&gt;&lt;br&gt;
We have a simple API that scrapes some data from a certain site and performs some heavy calculations on that data.&lt;br&gt;
Our API response is slow - and this is not great for our users.&lt;br&gt;
We know that this specific request may be received many times and that the information in our scraped site will only update every hour.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Our solution:&lt;/strong&gt;&lt;br&gt;
Caching!&lt;br&gt;
We can cache our first response for the next hour and avoid doing those slow calculations over and over again.&lt;br&gt;
Redis is very fast in memory data store that is perfect for this kind of task.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Implementation:&lt;/strong&gt;&lt;br&gt;
I will assume that you have Redis installed on your machine - if you don't, the Redis docs are very easy and simple to understand.&lt;br&gt;
First of all lets initiate our app with express&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//index.js
const express = require("express");

const app = express();

app.get("/heavy-task",(req, res) =&amp;gt; {
  const { searchTerm } = req.query;

  const result = heavyTask(searchTerm);

  res.status(200).json({ result });
});

app.listen(PORT, () =&amp;gt; {
  console.log("Server is listening on port " + PORT);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's install our Redis client to use Redis in our app - I'll be using &lt;code&gt;ioredis&lt;/code&gt;.&lt;br&gt;
We will initiate our client in a different file called &lt;code&gt;cache.js&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//cache.js

const Redis = require("ioredis");

const redisClient = new Redis();

redisClient.on("connect", () =&amp;gt; {
  console.log("Redis connected");
});

redisClient.on("error", (err) =&amp;gt; {
  console.log("Redis error", err);
})


module.exports = redisClient;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's import our &lt;code&gt;redisClient&lt;/code&gt; to the &lt;code&gt;index.js&lt;/code&gt; to use it on our handler.&lt;br&gt;
We will use the &lt;code&gt;SETEX&lt;/code&gt; method which accepts our key for the data store, a number that represents the number of seconds our data will live in the store - and lastly, the stored data as JSON.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//index.js
const express = require("express");
const redisClient = require("./cache.js");

const app = express();

app.get("/heavy-task",(req, res) =&amp;gt; {
  const { searchTerm } = req.query;

  const result = heavyTask(searchTerm);

  const resultJSON =  JSON.stringify(result);

  redisClient.setex(searchTerm, 3600, resultJSON);

  res.status(200).json({ result });
});

app.listen(PORT, () =&amp;gt; {
  console.log("Server is listening on port " + PORT);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great! now our data will be stored in Redis for the next hour.&lt;br&gt;
Now we will create our &lt;code&gt;checkCache&lt;/code&gt; middleware which will run each time the request is received and will simply ask Redis if the &lt;code&gt;searchTerm&lt;/code&gt; (key) exists - if so return the data - else &lt;code&gt;next()&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//middleware/checkCache.js
const redisClient = require("../cache.js");

const checkCache = (req, res, next) =&amp;gt; {
  const { searchTerm } = req.query;
  redisClient.get(searchTerm, (err, result) =&amp;gt; {
    if (err) {
      console.error(err);
    }
    if (result) {
      const cachedRes = JSON.parse(result);
      return res.status(200).json({cachedRes});
    } else {
      next();
    }
  });
};

module.exports = checkCache;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Implement our middleware in the handler.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//index.js
const express = require("express");
const redisClient = require("./cache.js");
const checkCache = require("./middleware/checkCache.js");

const app = express();

app.get("/heavy-task",checkCache,(req, res) =&amp;gt; {
  const { searchTerm } = req.query;

  const result = heavyTask(searchTerm);

  const resultJSON =  JSON.stringify(result);

  redisClient.setex(searchTerm, 3600, resultJSON);

  res.status(200).json({ result });
});

app.listen(PORT, () =&amp;gt; {
  console.log("Server is listening on port " + PORT);
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;That's It! now our requests are easily cached with Redis.&lt;br&gt;
Hope you found this simple guide helpful 😄&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>redis</category>
      <category>node</category>
    </item>
  </channel>
</rss>
