Posted by Arjun on Saturday 4th August 2018

API Caching with Redis and Node.js

cache How to Express.js Node.js Redis

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. Same technique you can use to avoid multiple database calls ..etc

We gonna create the express.js application to demonstrate 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 below command

npm install --save node-fetch express redis 

Create a file server.js with 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 you node server with node server.js command from your terminal, but before doing that ensure you have Redis server installed on your computer and update the Redis port if it is not running at default port 6379.

$ node server.js

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