Using a cache like Redis with node.js

Requirements:

Tutorial Write up:

Today I will be experimenting with a Redis database with a simple node.js server and basic API with express. To get started, you will need to start is to set up your project with whatever package manager you use. In this tutorial, I will use yarn.

yarn init

Next, we will need to install the node modules: express, body-parser, redis. To add the following packages just do:

yarn add express body-parser redis

After that create an index.js file at the root of your project. Then open the index.js file and then let's start. First, we will import the modules that we have just installed.

// Import the modules
var express = require('express');
var redis = require('redis');
var bodyParser = require('body-parser');
var app = express();

After that you need a Redis database, you can host it yourself however I will use the free tier on the Redis cloud app. To get a free cloud Redis database, click here. After that wait for the database to be created.

When created you will need to get the host URL, port and password. Then we will need to create a Redis client in our index.js file.

Please note if you are going to use this code make sure you use an environment variable for your details for the Redis database, but for this example, we will not use an environment variable.

// Creating your Redis client
var client = redis.createClient({
  host: '...', // Your host URL here
  port: 0000, // Your host port here
  password: '...' // Your host password here
})

// If the connection fails to the Redis database.
client.on('error', err => {
    console.log('Error ' + err);
});

We are halfway there! Now if you are just here for the Redis code then your pretty much set. However, for my experiment with the Redis database, I decided to create data with an express API and having to parse the body. So to do that I created two endpoints /create and /fetch. The /create requires two pieces of data, which is the key and value due to how the Redis database works. Then the /fetch retrieves data in the database and requires the key value of the data. The code would look like this:

// Express Settings
app.use(bodyParser.json());

// Set data to the Redis cloud

app.post('/create', (req, res) => {
  // Data sent with the request
  var key = req.body.key;
  var value = req.body.value;

  // The checks to see if there is any data.
  if (key === "" || key === undefined) return res.status(400).json({ message: "Missing data which is required" });
  if (value === "" || value === undefined) return res.status(400).json({ message: "Missing data which is required" });

  // Sets the data into the database.
  client.set(`${key}`, `${value}`, redis.print);

  // returns a success message!
  return res.status(200).json({
    message: "Data saved to redis cloud!"
  })
})

// Get data from the Redis cloud

app.post('/fetch', (req, res) => {
  // Data sent with the request
  var key = req.body.key;

  // The checks to see if there is any data.
  if (key === "" || key === undefined) return res.status(400).json({ message: "Missing data which is required" });

  // Gets the data from the database
  client.get(`${key}`, function(err, reply) {
    // Returns OK 
    return res.status(200).json({
      message: "Message from redis cloud!",
      returned: `${reply}`
    })
  });
})

Then that will be it, my experiment turned out amazing. I am shocked about how fast the database set and retrieved data. So that's it, thanks for reading!