Getting Started Node.js and Redis

Getting Started Node.js and Redis

Redis is the high-performance in-memory database used as data structure store. Redis supports hash, strings, lists and other complicated data structures

Redis is the high-performance in-memory database used as data structure store. Redis supports hash, strings, lists and other complicated data structures by maintaining very high performance.

Redis along with Node.js can be used as to solve various problems such as cache server or message broker. In this tutorial, we will cover popular and useful Redis commands along with interfacing it with Node.js.

Before we begin, let’s look at the installation of Redis on the various platform.


Installing Redis

To install Redis in Mac and Linux you can either do the manual build which is mentioned here OR if you are lazy like me then use these commands to install it on go.


On ubuntu

sudo apt-get install redis-server

On Mac using brew

brew install redis

Windows has no official package from Redis team but there is some port available which you can use at your own risk.

After installation, you can use the following command to start the Redis server.

redis-server

You should see the following screen.

To access the Redis command line interface, run the following command from a separate terminal.

redis-cli

You should see the following screen.

Try running “PING” command and you should recieve “PONG”.


Configuring Node.js and Redis

NodeRedis is very popular and high-performance Redis client for Node.js. It supports almost every syntaxes of Redis with high performance.

To install NodeRedis in your project, run following.

npm i --S redis

To access it in Node.js, you need to create Redis Client. Here is code snippet to do same.

var redis = require('redis');
var redisClient = redis.createClient({host : 'localhost', port : 6379});

redisClient.on('ready',function() {
console.log("Redis is ready");
});

redisClient.on('error',function() {
console.log("Error in Redis");
});

Save above code in file named app.js and run the program using the given command.

node app.js

If Redis is up and running, you should be able to see following screen.

If you want to add more configuration parameters related to Redis connection, here is the supported list.

Performing authentication to Redis

This is optional and only required when your Redis Server is protected by credentials. You must perform the authentication right after connecting to Redis using the following syntax.

redisClient.auth('password',function(err,reply) {
console.log(reply);
});
Storing key-value data in Redis

We have Node.js and Redis connected and talking to each other, let’s store some data into it. Like we have mentioned in the beginning of an article, Redis store and save data in key-value pair. Let’s look over some of them.


Storing strings

To store a simple string you can use following command.

redisClient.set("language","nodejs")

Here “language” will be the key with value as “nodejs”. After executing this command, you can check the values in Redis using the following command.

GET language

The callback is optional and if you want to receive the result of a command, you can provide the callback as follows.

redisClient.set("language","nodejs",function(err,reply) {
console.log(err);
console.log(reply);
});

To retrieve the value of keys you can run the Redis GET command with or without callback.

redisClient.get("language",function(err,reply) {
console.log(err);
console.log(reply);
});

Storing Object (Hash)

If you want to store something like this.

{
"webserver" : "expressjs",
"database" : "mongoDB",
"devops" : "jenkins"
}

Redis provides support to store them in one shot rather than storing it as strings pair. To store such hash in Redis we use hmset() command.

redisClient.hmset("tools","webserver","expressjs","database","mongoDB","devops","jenkins",function(er$
console.log(err);
console.log(reply);
});

redisClient.hgetall("tools",function(err,reply) {
console.log(err);
console.log(reply);
});


Storing List and Set

You can also store complex data structure such as List and Set. The only difference between List and Set is, List stores duplicate items while Set doesn’t.

Here is the code. The first parameter is the name of Set and List.

redisClient.rpush(["languages","angularjs","nodejs","go"],function(err,reply) {
console.log(err);
console.log(reply);
});

redisClient.sadd(["devopstools","jenkins","codeship","jenkins"],function(err,reply) {
console.log(err);
console.log(reply);
});

Here is the output.

null
3 // Count of list values.
null
2 // count of set values.

Notice that in Set, the number of values printed on screen is two but we actually passed three, 2 duplicate value of Jenkins got filtered.


Performing operations on Keys

After storing keys, Redis allows you to perform operations on them such as deleting keys, finding their existence or setting the expiry time.


Checking Keys existance

You can use exists() function to check the existance of key.

redisClient.exists('language',function(err,reply) {
if(!err) {
if(reply === 1) {
console.log("Key exists");
} else {
console.log("Does't exists");
}
}
});

Deleting Key

You can use del() function to delete the key from Redis.

redisClient.del('redisClient',function(err,reply) {
if(!err) {
if(reply === 1) {
console.log("Key is deleted");
} else {
console.log("Does't exists");
}
}
});

Setting Expiry time to Key

You can also set expiry time to keys in a second. Once expiry time reaches, Redis will automatically delete that key. You can use this for Session store very efficiently.

You can use expire() function to do same.

redisClient.expire('redisClient', 30); // Expirty time for 30 seconds.

Monitoring Redis

Redis provides the real-time feed of operations happening in it. To use and track it, run the following command from the separate terminal.

redis-cli monitor


Conclusion

We have covered Redis basics and installation along with most used commands. There are many more Redis features such as clustering etc and also some rich commands which you can learn here.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Node.js: The Complete Guide to Build RESTful APIs (2018)

Build a Basic CRUD App with Vue.js and Node

Building Live Streaming App with Node.js and React

The definitive Node.js handbook

New ECMAScript Modules in Node v12

Build a Node.js API with TypeScript

How to debug Node.js in a Docker container?

Front-end Developer Handbook 2019

Best Practices For Using TypeScript with Node.js

Originally published on https://codequs.com

Developing Modern APIs with Hapi.js, Node.js, and Redis

Developing Modern APIs with Hapi.js, Node.js, and Redis

Learn how to develop odern backend APIs with Hapi.js, Node.js, and Redis.

In this article, you are going to learn how to develop modern APIs with Hapi.js and Node.js, while using Redis as the persistence layer. As it is not possible to release an API without a security layer, you will also learn how to secure your application with Auth0. If needed, you can find the final code developed throughout this article in this GitHub repository.

What is Hapi.js?

Hapi.js is a framework for creating backend APIs. What is nice about Hapi.js, when compared to other solutions like Express, is the coding-by-configuration architecture. As you will see, most of the "coding" is actually done by tweaking the vast configuration interface that Hapi.js provides to developers. This approach helps to split the common aspects of HTTP from the handler.

What Is Redis and What Will You Build?

Redis is an open-source, in-memory data store that provides an interface so applications can manipulate data based on a key-value approach. As everything in a Redis database is simply a value accessible through a key, fetching data from it is extremely fast. This characteristic of Redis makes this database perfect for applications like to-do lists.

So, in this article, you will use Redis to act as the persistence layer of a backend API that supports a to-do list application. You won't develop the frontend application in this article, but you will soon, on an upcoming one.

Note: In this article, you are going to use Hapi.js 17. This version has breaking changes from version 16.

What Is Docker and Why Do You Care?

To keep your machine clean, you are not going to install Redis directly on your operating system. Instead, you are going to run Redis inside a Docker container. Docker, if you don't know, is a solution that enables users to run programs that operate completely isolated from each other. Docker achieves this by containerizing these programs into engines that work similarly to virtual machines.

However, containers are way less expensive (i.e., more lightweight) when compared to traditional virtual machines. For example, you can easily bootstrap a container that uses NGINX in front of a Node.js instance to serve a web app with 16MB or less. Also, Docker uses a file called dockerfile that facilitates the process of sharing containers configuration with others.

In this article, you are going to download and use a pre-built Redis container that allows you to use Redis fresh out of the box, with no setup.

Bootstrapping a Hapi.js API

Your API will contain the main server setup and individual files for each route you will need to define. Basically, you will create a project that contains the following structure:

  • src/: A directory that will hold code related to the server setup.
  • src/routes: A directory where you will define the endpoints of your API.

So, open a terminal, locate the directory where you want to store your project in, and run the following commands:

# e.g., move to your home dir (or anywhere else)
cd ~

# create a directory for your project
mkdir nodejs-hapijs-redis

# move into it
cd nodejs-hapijs-redis

# and create both subdirectories
mkdir -p src/routes

After that, you can initialize your main directory as an NPM project and install some dependencies on it:

# initialize this directory as an NPM project
npm init -y

# install your project's dependencies
npm install --save boom good good-console good-squeeze hapi hapi-auth-jwt2 hapi-require-https inert joi jwks-rsa lout node-env-file redis uuid vision

As you can see, you will need to install a considerable number of dependencies. Throughout this article, you will see how each one fits in. However, the following list gives a brief introduction to them:

  • boom: This is a library that tightly integrates with Hapi.js to throw HTTP-friendly error objects.
  • good: This is a library that you will plug into Hapi.js to monitor and report on a variety of server events.
  • good-console: This library is useful for turning good server events into formatted strings.
  • good-squeeze: This library is useful for filtering events based on the good event options.
  • hapi: This is the main package of Hapi.js itself.
  • hapi-auth-jwt2: This is an authentication scheme/plugin for Hapi.js apps using JSON Web Tokens.
  • hapi-require-https: This is a library that will help you force secure connections (i.e., HTTPS).
  • inert: This is a library that helps you serve static file and directory handlers in your Hapi.js API.
  • joi: This library introduces an object schema description language and a validator for JavaScript objects.
  • jwks-rsa: This library retrieves RSA public keys from a JWKS (JSON Web Key Set) endpoint.
  • lout: This library helps you create the API documentation for your Hapi.js backend.
  • node-env-file: This library parses and loads environment files into a Node.js environment (i.e., into the process.env object).
  • redis: This is a Redis client for Node.js applications.
  • uuid: This library generates RFC-compliant UUIDs in JavaScript.
  • vision: This library enables templates rendering for Hapi.js.

Now that you know what you just installed, open the package.json file that NPM created for you and replace its scripts property with this:

"scripts": {
  "start": "node index.js"
}

Note: You might also want to start Git (or any other version control system) now and start committing your work. It's always a good idea to use tools like Git to manage your source code.

Initializing Redis with Docker

As mentioned, you will bootstrap a Redis instance in your local machine with the help of Docker. Therefore, before proceeding you will have to install Docker locally. After installing it, you can test the installation by running the following command:

docker --version

If everything goes fine, you can issue this command to run Redis locally (in a Docker container, of course):

docker run --name nodejs-hapijs-redis \
    -p 6379:6379 \
    -d redis

If this is the first time you are running Redis locally with the help of Docker, this command will output Unable to find image 'redis:latest' locally in your terminal and will start downloading a Redis image from Docker Hub. For this article, you don't need to learn how Docker works. Issuing the command above suffices for you to move along. However, after you finish with this article, make sure you learn more about Docker. The tool is amazing.

Signing Up to Auth0

To start with a secure backend from scratch, you will sign up for a free Auth0 account now (i.e., if you don't have one yet) and you will configure your project to use this identity provider.

If you don't know, Auth0 is a global leader in Identity-as-a-Service (IDaaS) that provides thousands of enterprise customers with modern identity solutions. Alongside with the classic username and password authentication process, Auth0 allows you to add features like Social Login, Multi-factor Authentication, and much more with just a few clicks.

So, after you sign up for Auth0, you can head to the APIs section of your dashboard and click on Create API. Then, on the dialog that Auth0 shows, you will have to provide a Name for your API (e.g., "Hapi.js Tutorial") and an Identifier (e.g., http://localhost:3000). The name of your API is just a label so you can easily remember what the API is about. The identifier is a string that you will use while configuring your backend. This identifier doesn't really have to be an URL, as Auth0 won't call it in any moment, but it's advised to use one.

After filling out the form, click on Create so Auth0 finishes the creation for you.

Creating an environment file

As you will have the configuration for your Auth0 account, you will keep it in a separate file so you can easily switch between a production and testing environment. As such, create a file called .env in your project root and put the following contents in it:

AUTH0_AUDIENCE=http://localhost:3000
AUTH0_DOMAIN=<YOUR_AUTH0_DOMAIN>
HOST=localhost
PORT=3000
REDIS_HOST=localhost
REDIS_PORT=6379
SSL=false

Replace <YOUR_AUTH0_DOMAIN> with the domain you chose while creating your Auth0 account (e.g., blog-samples.auth0.com). The other configuration variables will work in your local environment, unless you chose another identifier for your API. If that is the case, you will have to set the correct value to the AUTH0_AUDIENCE variable.

Note: The SSL variable above defines if your API will accept only requests through a secure channel (i.e., HTTPS) or not. This variable will be used by the hapi-require-https library that you installed before.

Creating the Hapi.js Server

With the environment variables properly defined, you will have to create a script to start your Hapi.js server. To do so, create a file called index.js in the project root (i.e., in the nodejs-hapijs-redis directory) and add the following code into it:

require('node-env-file')(`${__dirname}/.env`);

const redis = require('redis');
const createServer = require('./src/server');
const {promisify} = require('util');

const start = async () => {
  const server = await createServer(
    {
      port: process.env.PORT,
      host: process.env.HOST,
    },
    {
      enableSSL: process.env.SSL === 'true',
    }
  );

  const redisClient = redis.createClient(
    {
      host: process.env.REDIS_HOST,
      port: process.env.REDIS_PORT,
    }
  );

  redisClient.lpushAsync = promisify(redisClient.lpush).bind(redisClient);
  redisClient.lrangeAsync = promisify(redisClient.lrange).bind(redisClient);
  redisClient.llenAsync = promisify(redisClient.llen).bind(redisClient);
  redisClient.lremAsync = promisify(redisClient.lrem).bind(redisClient);
  redisClient.lsetAsync = promisify(redisClient.lset).bind(redisClient);

  redisClient.on("error", function (err) {
    console.error("Redis error.", err);
  });

  server.app.redis = redisClient;

  await server.start();

  console.log(`Server running at: ${server.info.uri}`);
  console.log(`Server docs running at: ${server.info.uri}/docs`);
};

process.on('unhandledRejection', (err) => {
  console.error(err);
  process.exit(1);
});

start();

As you can see, the first thing your script does is to load the environment variables you just defined. Then, it uses a function called createServer to, well, create a server. After that, the script creates a client to Redis and uses the promisify function provided by Node.js to make the functions provided by the client return JavaScript Promises (using promises, and the new async/await syntax, will make your life much easier). Also, you bind the Redis object to server.app.redis so you have access to it in the routes to store and retrieve data.

Perhaps you didn't realize (or perhaps you did), but the createServer function used in the script above doesn't exist yet. This function, as stated on line #4, is expected to be defined on a module called server in the src directory.

Therefore, you can create the src/server.js file and add the following code to it:

const Hapi = require('hapi');
const jwksRsa = require('jwks-rsa');

const validateFunc = async (decoded) => {
  return {
    isValid: true,
    credentials: decoded,
  };
};

module.exports = async (serverOptions, options) => {
  const server = Hapi.server(
    Object.assign({
      port: 3001,
      host: 'localhost',
      routes: {
        cors: {
          origin: ['*'],
        },
      },
    }, serverOptions),
  );

  // Redirect to SSL
  if (options.enableSSL) {
    console.log('Setting SSL');
    await server.register({plugin: require('hapi-require-https')});
  } else {
    console.log('Not setting SSL');
  }

  await server.register([
    require('vision'),
    require('inert'),
    {
      plugin: require('lout'),
      options: {
        endpoint: '/docs',
      },
    },
    {
      plugin: require('good'),
      options: {
        ops: {
          interval: 1000,
        },
        reporters: {
          consoleReporter: [
            {
              module: 'good-squeeze',
              name: 'Squeeze',
              args: [{response: '*'}],
            },
            {
              module: 'good-console',
            },
            'stdout',
          ],
        },
      },
    },
  ]);

  await server.register(require('hapi-auth-jwt2'));

  server.auth.strategy('jwt', 'jwt', {
    complete: true,
    key: jwksRsa.hapiJwt2KeyAsync({
      cache: true,
      rateLimit: true,
      jwksRequestsPerMinute: 5,
      jwksUri: `https://${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`,
    }),
    verifyOptions: {
      audience: process.env.AUTH0_AUDIENCE,
      issuer: `https://${process.env.AUTH0_DOMAIN}/`,
      algorithms: ['RS256'],
    },
    validate: validateFunc,
  });

  server.auth.default('jwt');

  server.route(require('./routes.js'));

  return server;
};

The main export from this code is a function that creates and returns a valid Hapi.js server. This function starts by accepting arguments from the index.js file and by creating the server. Then, it provide some default configurations like port and host to make sure that everything goes fine if the caller doesn't specify these variables, but soon it replaces them with the ones provided by the caller (if any).

After creating the Hapi.js server (Hapi.server()), this script decides, based on the configuration passed, if it is going to use SSL or not. Then, the script configures the plugins you installed before (e.g., vision, inert, and lout) in your Hapi.js server.

Finally, the script secures the server by using the jwt strategy (server.auth.strategy('jwt', ...)) and by making it the default authentication method (server.auth.default('jwt')).

The function validateFunc (defined at the top of the script) is given users' credentials and returns an object telling Hapi.js whether these users have access to the current resource or not. In this simple example, you allow all users access if they have a valid token, but you can be more restrictive by refactoring this function.

The last thing this script does, besides returning an instance of the Hapi.js file, is to define that it will load the endpoint (also known as routes) from a module called routes. You will define this module in the next section.

Defining Routes on Hapi.js

Now, it is time to learn how to define endpoints (i.e., routes) in your Hapi.js server. In the server module, you called the server.route function, which accepts an array of routes for your server. As such, you could simply define these routes directly into the server module. However, to make the code more readable and organized, you will put each route in a different file.

To do so, create a file called src/routes.js and copy the following into it:

module.exports = [

  './routes/todo_get',
  './routes/todo_post',
  './routes/todo_delete',

].map((elem) => require(elem));

This code maps over each filename and returns an array of imported routes. As you can imagine, you still have to define these files and routes.

Defining a Route to Post new Items

For your first route, you will create an endpoint that enables users to add new items to their to-do lists. To do so, make a file called src/routes/todo_post.js with the following contents:

const Joi = require('joi');
const Boom = require('boom');

module.exports = {
  method: 'POST',
  path: '/todo',
  options: {
    auth: 'jwt',
    validate: {
      payload: {
        item: Joi.string().required().notes('Text to store in list')
      },
    },
    description: 'Add item',
    notes: 'Add an item to the list',
    tags: ['api'],
  },
  handler: async (request, h) => {
    let {sub: redispath} = request.auth.credentials;
    let {item: redisvalue} = request.payload;
    let {redis} = request.server.app;

    try {

      let count = await redis.lpushAsync(redispath, redisvalue);

      return h.response({
        count
      }).code(201);

    } catch (e) {
      return Boom.badImplementation(e);
    }
  }
};

The export from this file is a JSON object that represents a route for Hapi.js. The method and path properties tell Hapi.js what HTTP method and what route is required to call the handler code. In the options, you specify jwt as the authentication required to access this route. The description, notes, and tags document the route for others using it.

The validate object is an extremely useful courtesy of the joi library. This allows you to specify what inputs are required for the route and, if not met, Hapi.js will automatically throw an error for you. All that is required for this route is an item that comes as the payload of requests. This item must be a string and is required (string().required()).

Finally, the handler runs your route and returns a value to Hapi.js. You use the JWT subject as the key for the Redis key-value pair, and the value of this key is the string sent by the user. You use the new promisified Redis functions to add the item to Redis, and you return the number of items in the array (with a 201 response code).

If anything goes wrong, your Hapi.js server will send an HTTP error code back using the Boom library.

Defining a Route to Delete Items

To allow users to delete items, create a file called src/routes/todo_delete.js with the following contents:

const Joi = require('joi');
const Boom = require('boom');

module.exports = {
  method: 'DELETE',
  path: '/todo',
  options: {
    auth: 'jwt',
    validate: {
      payload: {
        index: Joi.number().min(0).required().notes('Index to delete'),
      },
    },
    description: 'Delete item',
    notes: 'Delete an item from the todo list',
    tags: ['api'],
  },
  handler: async (request, h) => {
    let {sub: redispath} = request.auth.credentials;
    let {index: redisindex} = request.payload;
    let {redis} = request.server.app;

    try {
      await redis.lsetAsync(redispath, redisindex, '__DELETE__');
      await redis.lremAsync(redispath, 1, '__DELETE__');

      return h.response({}).code(200);
    } catch (e) {
      return Boom.badImplementation(e);
    }
  }
};

The route is very similar to the POST route. You define the endpoint as an HTTP DELETE route with a required index parameter to delete a value from Redis. To delete the item from Redis by index, you first overwrite the value of that entry, and then delete entries with that new value.

What is Hypertext Application Language (HAL)?

When you define your final route for retrieving the todo items, you will borrow some features from the HAL specification. This spec is designed to make it easy to traverse APIs without having to guess endpoints.

For your case, you will page the results when retrieving items, so you will include a link to the next page of results in the response. This way, the client applications that use your API won't have to generate the links themselves.

Defining a Route to Get All Items

Finally, to define an endpoint where users will be able to get all their to-do items, create a file called src/routes/todo_get.js with the following contents:

const Joi = require('joi');
const Boom = require('boom');

module.exports = {
  method: 'GET',
  path: '/todo',
  options: {
    auth: 'jwt',
    validate: {
      query: {
        start: Joi.number().min(0).default(0).notes('Start index of results inclusive'),
        results: Joi.number().min(1).max(100).default(10).notes('Number of results to return'),
      },
    },
    description: 'Get items',
    notes: 'Get items from todo list paged',
    tags: ['api'],
  },
  handler: async (request, h) => {
    let {redis} = request.server.app;
    let {sub: redispath} = request.auth.credentials;
    let {start, results} = request.query;

    try {
      let value = await redis.lrangeAsync(redispath, start, start + (results - 1));
      let count = await redis.llenAsync(redispath);

      if (!value) value = [];

      return h.response({
        nextlink: `${request.url.pathname}?start=${start + results}&results=${results}`,
        value,
        count
      });
    } catch (e) {
      return Boom.badImplementation(e);
    }
  }
};

This module (or file) defines a GET HTTP route with two optional query string parameters (with default values set). By using these parameters, your client can specify the first element (start index) and the number of results they need. Note that this script gets the results from Redis and also the total number of results. This information is important so the client can display how many items the user has.

In the response, you add a nextlink property with the API URL to call for the next set of results.

Running and Using your Hapi.js API

That's it! You just finished creating your Node.js backend API with the help of Hapi.js and Redis. With all these files in place, you can take your API for a spin. To do so, issue the following command on the terminal (just make sure you are in the correct directory: nodejs-hapijs-redis):

npm start

Then, if you go to the /docs resource, you will see the documentation of your Hapi.js API:

Now, to test if your endpoints are really secured, you can issue the following curl commands:

curl http://localhost:3000/todo

curl -X POST -H 'Content-Type: application/json' -d '{
  "item": "It should not work."
}' http://localhost:3000/todo

Both commands above should return the following response:

{
  "statusCode": 401,
  "error": "Unauthorized",
  "message": "Missing authentication"
}

That is, your server is telling you that it is expecting you to be authenticated somehow. The server doesn't specify that it's expecting an access token from Auth0 because you shouldn't be adding details like that about your services. However, you know that this is what you need.

So, there are multiple ways to fetch a token from Auth0. The strategy that you will use will depend on what context you are in. For example, if you are on a Single Page Application (SPA), you will use what is called the Implicit Grant. If you are on a native, mobile application, you will use the Authorization Code Grant Flow with PKCE. However, for a simple test like this one, you can use your Auth0 dashboard to get one.

So, head back to the APIs section in your Auth0 dashboard, click on the API you created before, and then click on the Test section of this API. There, you will find a button called Copy Token. Click on this button to copy an access token to your clipboard.

Then, with this token in your clipboard, go back to your terminal and execute the following commands:

# set a variable with your access token
ACCESS_TOKEN=<YOUR_ACCESS_TOKEN>

# use the token to insert an item
curl -X POST -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer '$ACCESS_TOKEN -d '{
  "item": "Learn about more about Docker, Auth0, and Redis."
}' http://localhost:3000/todo

Note: You will have to replace <YOUR_ACCESS_TOKEN> with the token copied from Auth0.

The second command, the one that issues an HTTP request with your token, will create a new item in your to-do list so you can remember that you have to "learn about more about Docker, Auth0, and Redis." As the response to this request, your API will send this to you:

{
  "count": 1
}

This answer tells you that you have a single record on your to-do list right now, as you would expect. Now, to see this item, you can issue the following command:

# in the same terminal because you need $ACCESS_TOKEN
curl -H 'Authorization: Bearer '$ACCESS_TOKEN http://localhost:3000/todo

This command will output the following response from the Hapi.js API:

{
  "nextlink": "/todo?start=10&results=10",
  "value": ["Learn about more about Docker, Auth0, and Redis."],
  "count": 1
}

As you can see, your to-do item was properly inserted. Now, to remove this item, you can issue this command:

curl -X DELETE -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer '$ACCESS_TOKEN -d '{
  "index": 0
}' http://localhost:3000/todo

In this case, you are issuing a DELETE request with index equals 0 so your API remove the first element from your to-do list. Cool, you just used your API for the first time!

Conclusion and Next Steps

In this article, you learned how to create modern APIs with Hapi.js, Node.js, and Redis. Also, you learned how to integrate your API with Auth0 to take advantage of the state-of-the-art security provided by this company. All of that, without struggling too much.

However, you wouldn't expect end-users to use a REST API directly through the command-line interface or through generic HTTP clients like Postman, would you? As such, in the next article, you will learn how to create a Single Page Application to interact with your API. To create this application, you will use a modern approach based on web components and LitElement. Stay tuned!

30s ad

Getting Started with NodeJS for Beginners

Learn Nodejs by building 12 projects

Supreme NodeJS Course - For Beginners

NodeJS & MEAN Stack - for Beginners - In Easy way!

Node.js for beginners, 10 developed projects, 100% practical

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Express

With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.

Meteor

Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.

Koa

Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.

Sails

Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).

Nest

Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.

LoopBack

LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).

Hapi

Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

An introduction to Caching with Redis in Node.js application

An introduction to Caching with Redis in Node.js application

Caching is the process of storing data into a cache. In this article, We will discuss caching with Redis in Node.js application.

A cache is a temporary data store where data is kept for later use. It is not a good approach if we go to database and query for the same data every time. So in this scenerio, we save the data in cache for the first time and retrieve data from cache inplace of database. It increases the app performance a lot.

For a web developer, it's very necessary to increase the performance and make the app respond faster, And for achieving this we use caching at the server end.

What is Redis?

Official doc says - Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. Redis has built-in replication, Lua scripting, LRU eviction, transactions and different levels of on-disk persistence, and provides high availability via Redis Sentinel and automatic partitioning with Redis Cluster.

Let's Get Started Step 1: Install Redis over local machine

At first, Install **Redis **over local system with below command over **ubuntu **system.

sudo apt-get install redis-server

Step 2: Create Node.js application

Create a project folder, redis-nodejs, move to the folder over terminal and create a nodejs app with default package.json file with below command over terminal.

npm init --yes

Step 3: Install required packages

Now install express, redis, node-fetch npm packages with below command:

npm i express node-fetch redis 

Step 4: update server.js file

create a file, server.js inside project folder and put the below code inside this file:

const express = require('express');
const app = express() // create express app
 
const fetch = require("node-fetch");
const redis = require('redis');
 
 
 
const client = redis.createClient(6379); //connect redis client with local instance.
 
// echo redis errors to the console
client.on('error', (err) => {
console.log("Error " + err)
});
 
// get user list
app.get('/user-list', (req, res) => {
const todoRedisKey = 'user:userList';
// Try fetching the result from Redis first in case we have it cached
return client.get(todoRedisKey, (err, users) => {
 
// If that key exists in Redis store
if (users) {
console.log('fetching data from cache-----');
return res.json({ source: 'cache', data: JSON.parse(users) })
 
} else { // Key does not exist in Redis store
console.log('fetching data from api-----');
// Fetch directly from remote api
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json())
.then(users => {
 
// Save the API response in Redis store, data expire time in 3600 seconds, it means one hour
client.setex(todoRedisKey, 3600, JSON.stringify(users))
 
// Send JSON response to client
return res.json({ source: 'api', data: users })
 
})
.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)
});

Step 5: Run the Node.js application

Type below command over terminal in project folder.

node  server.js

Now go to the browser at and

Enter url: http://localhost:3000/user-list in the url. When yo will fetch the data for the first time, then data will come after calling the api and from the next request, data will fetch from the cache only. And if request time of first request 4000 ms then from the next it will take around 1000 ms.

Conclusion

**Redis **is very powerful in-memory data-store that we can use in our applications. It’s very simple to save and get data without much overhead.

So in this article, We understand the implementation of **Redis **in Node.js application with a very basic example