Redis in Node.js 2024
Ifeanyi Chima
Posted on March 13, 2024
In this aricle, we will take a look at how to add redis caching to your production level node.js code to make it more performant.
For data that is frequently needed or retrieved by app users, a cache would serve as a temporary data store for quick and fast retrieval without the need for extra database round trips. Reference
- Redis can be used as a cache mechanism
- Redis can be used as a persistent storage space.
Installation
To install Redis on our local machines, we can download the latest binaries available
First, extract the zip file, then install redis-server.exe
. You can also run the redis-cli
.
On your redis-cli
you can set executables
- set name Elon Musk
- get name
Note: You must always turn on your redis-server
Nodejs
Initialize your project
In your project directory, navigate to the terminal and run the following commands:
mkdir server
cd server
npm run init -y
npm install express node-fetch redis
Redis Client
- Import the package and create an instance
- Set a Redis port
- Create and connect a Redis Client
// src/index.js
import { createClient } from "redis/dist/index.js";
const app = express();
app.use(express.json())
// redis port
const REDIS_PORT = 6379;
// create redis client
export const client = createClient();
(async () => {
await client.on('error', err => console.log('Error ' + err));
await client.connect();
})();
const getRepos = async (req, res) => {
let {username} = req.params
let result;
try{
// use the key to get data from the cache
const cachedData = await client.get("new key");
// If data exists in the cache, return it
if(cachedData) {
result = JSON.parse(cachedData);
} else {
result = await fetch(`https://api.github.com/users/${username}`);
console.log(result)
if (result?.length === 0 || !result) {
return res.status(200).send("API returned an empty array");
}
// set data to redis
await client.set("cachedData", JSON.stringify(result));
}
res.status(200).json(result);
} catch(error) {
console.error(error);
res.status(404).send("Data unavailable");
}
}
app.get("/repos/:username", getRepos);
app.listen(PORT, () => {
console.log(`server is listening on ${PORT}`)
})
After adding redis to your code, the time taken to make a request to your API is significantly cut down.
Thank you, Please follow me
Posted on March 13, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.