Skip to content

API Caching with Redis and Node.js

Last updated on November 21, 2022

In this post, I would like to show you, how we can use Redis to Cache APIs response to avoid multiple hits to the API. The same technique you can use to avoid multiple database calls ..etc

We gonna create the express.js application to demonstrate the Redis cache example.

let’s create a folder called redisCahceExample

$ mkdir redisCahceExample

After creating, change the directory to redisCahceExample

$ cd redisCahceExample

Now initialize the project with npm init command

$ npm init --yes

--yes tells npm to use the default options while generating the package.json so you are not asked any questions

After running the command above, you should have a package.json file in the redisCahceExample directory.

Now install the Express, Redis, and node-fetch npm modules with the below command

npm install --save node-fetch express redis 

Create a file server.js with the following code in the redisCahceExample directory.

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

// create express application instance
const app = express()

// create and connect redis client to local instance.
const client = redis.createClient(6379)

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

// get todos list
app.get('/todos', (req, res) => {

    // key to store results in Redis store
    const todoRedisKey = 'user:todos';

    // Try fetching the result from Redis first in case we have it cached
    return client.get(todoRedisKey, (err, todos) => {

        // If that key exists in Redis store
        if (todos) {

            return res.json({ source: 'cache', data: JSON.parse(todos) })

        } else { // Key does not exist in Redis store

            // Fetch directly from remote api
            fetch('httpss://jsonplaceholder.typicode.com/todos')
                .then(response => response.json())
                .then(todos => {

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

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

                })
                .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)
});

All set now start your node server with the node server.js command from your terminal, but before doing that ensure you have the Redis server installed on your computer and update the Redis port if it is not running at default port 6379 in your code.

$ node server.js

Now head over to the browser with http://localhost:3000, at the first visit in the response object you should see the source key value as API and if you refresh the page you should see the source key value as a cache.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments