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:


Replace <YOUR_AUTH0_DOMAIN> with the domain you chose while creating your Auth0 account (e.g., 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:


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);
  }); = redisClient;

  await server.start();

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

process.on('unhandledRejection', (err) => {


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 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(
      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([
      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',

  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,



  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 = [


].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} =;

    try {

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

      return h.response({

    } 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} =;

    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} =;
    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}`,
    } 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

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


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


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.

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step)

Node.js for Beginners - Learn Node.js from Scratch (Step by Step) - Learn the basics of Node.js. This Node.js tutorial will guide you step by step so that you will learn basics and theory of every part. Learn to use Node.js like a professional. You’ll learn: Basic Of Node, Modules, NPM In Node, Event, Email, Uploading File, Advance Of Node.

Node.js for Beginners

Learn Node.js from Scratch (Step by Step)

Welcome to my course "Node.js for Beginners - Learn Node.js from Scratch". This course will guide you step by step so that you will learn basics and theory of every part. This course contain hands on example so that you can understand coding in Node.js better. If you have no previous knowledge or experience in Node.js, you will like that the course begins with Node.js basics. otherwise if you have few experience in programming in Node.js, this course can help you learn some new information . This course contain hands on practical examples without neglecting theory and basics. Learn to use Node.js like a professional. This comprehensive course will allow to work on the real world as an expert!
What you’ll learn:

  • Basic Of Node
  • Modules
  • NPM In Node
  • Event
  • Email
  • Uploading File
  • Advance Of Node

How to Use Express.js, Node.js and MongoDB.js

How to Use Express.js, Node.js and MongoDB.js

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

In this post, I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database. It will also show all items that have been entered into the database.

Creating a Node Application

To get started I would recommend creating a new database that will contain our application. For this demo I am creating a directory called node-demo. After creating the directory you will need to change into that directory.

mkdir node-demo
cd node-demo

Once we are in the directory we will need to create an application and we can do this by running the command
npm init

This will ask you a series of questions. Here are the answers I gave to the prompts.

The first step is to create a file that will contain our code for our Node.js server.

touch app.js

In our app.js we are going to add the following code to build a very simple Node.js Application.

var express = require("express");
var app = express();
var port = 3000;
app.get("/", (req, res) => {
&nbsp;&nbsp;res.send("Hello World");
app.listen(port, () => {
  console.log("Server listening on port " + port);

What the code does is require the express.js application. It then creates app by calling express. We define our port to be 3000.

The app.use line will listen to requests from the browser and will return the text “Hello World” back to the browser.

The last line actually starts the server and tells it to listen on port 3000.

Installing Express

Our app.js required the Express.js module. We need to install express in order for this to work properly. Go to your terminal and enter this command.

npm install express --save

This command will install the express module into our package.json. The module is installed as a dependency in our package.json as shown below.

To test our application you can go to the terminal and enter the command

node app.js

Open up a browser and navigate to the url http://localhost:3000

You will see the following in your browser

Creating Website to Save Data to MongoDB Database

Instead of showing the text “Hello World” when people view your application, what we want to do is to show a place for user to save data to the database.

We are going to allow users to enter a first name and a last name that we will be saving in the database.

To do this we will need to create a basic HTML file. In your terminal enter the following command to create an index.html file.

touch index.html

In our index.html file we will be creating an input filed where users can input data that they want to have stored in the database. We will also need a button for users to click on that will add the data to the database.

Here is what our index.html file looks like.

<!DOCTYPE html>
    <title>Intro to Node and MongoDB<title>

    <h1>Into to Node and MongoDB<&#47;h1>
    <form method="post" action="/addname">
      <label>Enter Your Name<&#47;label><br>
      <input type="text" name="firstName" placeholder="Enter first name..." required>
      <input type="text" name="lastName" placeholder="Enter last name..." required>
      <input type="submit" value="Add Name">

If you are familiar with HTML, you will not find anything unusual in our code for our index.html file. We are creating a form where users can input their first name and last name and then click an “Add Name” button.

The form will do a post call to the /addname endpoint. We will be talking about endpoints and post later in this tutorial.

Displaying our Website to Users

We were previously displaying the text “Hello World” to users when they visited our website. Now we want to display our html file that we created. To do this we will need to change the app.use line our our app.js file.

We will be using the sendFile command to show the index.html file. We will need to tell the server exactly where to find the index.html file. We can do that by using a node global call __dirname. The __dirname will provide the current directly where the command was run. We will then append the path to our index.html file.

The app.use lines will need to be changed to
app.use("/", (req, res) => {   res.sendFile(__dirname + "/index.html"); });

Once you have saved your app.js file, we can test it by going to terminal and running node app.js

Open your browser and navigate to “http://localhost:3000”. You will see the following

Connecting to the Database

Now we need to add our database to the application. We will be connecting to a MongoDB database. I am assuming that you already have MongoDB installed and running on your computer.

To connect to the MongoDB database we are going to use a module called Mongoose. We will need to install mongoose module just like we did with express. Go to your terminal and enter the following command.
npm install mongoose --save

This will install the mongoose model and add it as a dependency in our package.json.

Connecting to the Database

Now that we have the mongoose module installed, we need to connect to the database in our app.js file. MongoDB, by default, runs on port 27017. You connect to the database by telling it the location of the database and the name of the database.

In our app.js file after the line for the port and before the app.use line, enter the following two lines to get access to mongoose and to connect to the database. For the database, I am going to use “node-demo”.

var mongoose = require("mongoose"); mongoose.Promise = global.Promise; mongoose.connect("mongodb://localhost:27017/node-demo");

Creating a Database Schema

Once the user enters data in the input field and clicks the add button, we want the contents of the input field to be stored in the database. In order to know the format of the data in the database, we need to have a Schema.

For this tutorial, we will need a very simple Schema that has only two fields. I am going to call the field firstName and lastName. The data stored in both fields will be a String.

After connecting to the database in our app.js we need to define our Schema. Here are the lines you need to add to the app.js.
var nameSchema = new mongoose.Schema({   firstName: String,   lastNameName: String });

Once we have built our Schema, we need to create a model from it. I am going to call my model “DataInput”. Here is the line you will add next to create our mode.
var User = mongoose.model("User", nameSchema);

Creating RESTful API

Now that we have a connection to our database, we need to create the mechanism by which data will be added to the database. This is done through our REST API. We will need to create an endpoint that will be used to send data to our server. Once the server receives this data then it will store the data in the database.

An endpoint is a route that our server will be listening to to get data from the browser. We already have one route that we have created already in the application and that is the route that is listening at the endpoint “/” which is the homepage of our application.

HTTP Verbs in a REST API

The communication between the client(the browser) and the server is done through an HTTP verb. The most common HTTP verbs are

The following table explains what each HTTP verb does.

HTTP Verb Operation
GET Read
POST Create
PUT Update

As you can see from these verbs, they form the basis of CRUD operations that I talked about previously.

Building a CRUD endpoint

If you remember, the form in our index.html file used a post method to call this endpoint. We will now create this endpoint.

In our previous endpoint we used a “GET” http verb to display the index.html file. We are going to do something very similar but instead of using “GET”, we are going to use “POST”. To get started this is what the framework of our endpoint will look like."/addname", (req, res) => {
Express Middleware

To fill out the contents of our endpoint, we want to store the firstName and lastName entered by the user into the database. The values for firstName and lastName are in the body of the request that we send to the server. We want to capture that data, convert it to JSON and store it into the database.

Express.js version 4 removed all middleware. To parse the data in the body we will need to add middleware into our application to provide this functionality. We will be using the body-parser module. We need to install it, so in your terminal window enter the following command.

npm install body-parser --save

Once it is installed, we will need to require this module and configure it. The configuration will allow us to pass the data for firstName and lastName in the body to the server. It can also convert that data into JSON format. This will be handy because we can take this formatted data and save it directly into our database.

To add the body-parser middleware to our application and configure it, we can add the following lines directly after the line that sets our port.

var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
Saving data to database

Mongoose provides a save function that will take a JSON object and store it in the database. Our body-parser middleware, will convert the user’s input into the JSON format for us.

To save the data into the database, we need to create a new instance of our model that we created early. We will pass into this instance the user’s input. Once we have it then we just need to enter the command “save”.

Mongoose will return a promise on a save to the database. A promise is what is returned when the save to the database completes. This save will either finish successfully or it will fail. A promise provides two methods that will handle both of these scenarios.

If this save to the database was successful it will return to the .then segment of the promise. In this case we want to send text back the user to let them know the data was saved to the database.

If it fails it will return to the .catch segment of the promise. In this case, we want to send text back to the user telling them the data was not saved to the database. It is best practice to also change the statusCode that is returned from the default 200 to a 400. A 400 statusCode signifies that the operation failed.

Now putting all of this together here is what our final endpoint will look like."/addname", (req, res) => {
  var myData = new User(req.body);
    .then(item => {
      res.send("item saved to database");
    .catch(err => {
      res.status(400).send("unable to save to database");
Testing our code

Save your code. Go to your terminal and enter the command node app.js to start our server. Open up your browser and navigate to the URL “http://localhost:3000”. You will see our index.html file displayed to you.

Make sure you have mongo running.

Enter your first name and last name in the input fields and then click the “Add Name” button. You should get back text that says the name has been saved to the database like below.

Access to Code

The final version of the code is available in my Github repo. To access the code click here. Thank you for reading !