Redis in Node.js 2024
Tags: redishackathon, javascript, node, webdev
Published: 2024-03-13 13:24:32

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](https://dev.to/bnevilleoneill/a-guide-to-fully-understanding-redis-1gjc)

- 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](https://github.com/dmajkic/redis/downloads)

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`**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lxfdb6uzueat87ec6k8x.gif)

#### 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


```javascript

// 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.





<a href="https://www.buymeacoffee.com/ifeanyichima" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

**Thank you, Please follow me**

[![HTML](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://linkedin.com/in/ifeanyi-thankgod-chima)&nbsp;[![GitHub](https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/masterifeanyi)