loading...

Redis for Caching in Node js

emmygozi profile image Ahaiwe Emmanuel Updated on ・3 min read

Why use Redis?
Making database request and persisting data in an application can become costly as an application grows in the number of features and users it has. Think of the load time it takes for your browser to open a new page. We can observe that it can take a while to load, especially if internet connectivity is poor. Imagine your application making these request to services like a database under the hood. One can end up with an application with bad user experience because it might take a long time to load and navigate pages. Redis is the answer to this concern.

Redis
Is an in-memory data structure store, used as a database, cache or message broker. It is open-source so you can make contributions! Yaay :)

Downloading and Installing Redis MacOS
Using Homebrew run:

brew install redis

Launch Redis on Computer Start
ln -sfv /usr/local/opt/redis/*.plist ~/Library/LaunchAgents

Test if Redis is Running

redis-cli ping

If it replies "pong" then bravo! we are good to go.

Downloading and Installing Redis on Windows
Visit https://github.com/ServiceStack/redis-windows/tree/master/downloads
and download the latest zip file. Run the executable script called Redis server.

Add “C:\Program Files\Redis\” to the end of the variable value and click “OK.” if it doesn't already exist.

Test if Redis is Running

redis-cli ping

If it replies "pong" then bravo! we are good to go.

Caching Database Requests with Redis
Assumption - you have node installed on your device.

Create a folder and call it redis-tut or whatever you like :)

Run:

npm install express node-fetch redis

to install the needed packages for this tutorial.

Create a file called redis.js in that folder.

Import the packages and instantiate them like this:

const express = require('express');
const fetch = require('node-fetch');
const redis = require('redis');
const PORT = process.env.PORT || 5000;
const REDIS_PORT = process.env.PORT || 6379;
const client = redis.createClient(REDIS_PORT);
const app = express();

Set response to request

function setResponse(username, repos) {
return `<h2>${username} has ${repos} Github repos</h2>`;
}

Make a get request to get all public repositories of a given github username:

async function getAllPublicRepos(req, res, next) {
try {
console.log('Fetching Public Data of Supplied Username...');
const { username } = req.params;
const response = await
fetch(`https://api.github.com/users/${username}`);
const data = await response.json();
const repos = data.public_repos;
// Set data to Redis called username
client.setex(username, 3600, repos);
res.send(setResponse(username, repos));
} catch (err) {
console.error(err);
res.status(500);
}
}

Create a middleware for data caching

function cache(req, res, next) {
const { username } = req.params;
client.get(username, (err, data) => {
if (err) throw err;
if (data !== null) {
res.send(setResponse(username, data));
} else {
next();
}
});
}

Initialize API routes for use in the application

app.get('/repos/:username', cache, getRepos);
app.listen(5000, () => {
console.log(`App listening on port ${PORT}`);
});

Visit

http://localhost:5000/repos/{any-github-repo-username}

to test the application. You should see a summary of the number of public repositories a given user has.

Inspect the page and switch to the network tab. Refresh the page. You would notice that the page loads immediately because the data values have been cached. Hurray!!!

If you followed through to this point, congratulations! You have successfully set up Redis for caching in Nodejs.

Please share your comment and ways this tutorial could be improved. Thank you for your time :)

Credit: A lot of this tutorial was influenced by Brad Traversy

Discussion

pic
Editor guide
Collapse
cuongrep profile image
Kane Le

Instead of app.get('/repos/:username', cache, getRepos),
it should be app.get('/repos/:username', cache, getAllPublicRepos)