Apps.js Overview – Node.js API With TDD Tutorial

Before we begin the code development for the REST API, we will go over the apps.js file and its contents. This javascript is the main file that gets invoked by the server file (bin/www) to start the Node.js application.

The first few lines in the apps.js are for importing some dependent modules into this file.

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

We will be using these modules in our app for various reasons which we will go through in the coming sections.

App Level Dependent Modules / Middlewares

Let’s go through the modules that are imported in the apps.js. These are used with this file because these dependencies are needed at the app level.

1. express module

This one is the main module for our application as it provides the web application framework packages and also RESTful services related modules like HTTP and other middleware.

After a few lines as below, there is an instance created from this module which will be used to describe and define the behavior of the API. Below are the lines that are defining our application.

var app = express();

Once the instance of the express application is created with the variable app, we will be able to use express application’s capabilities to define and shape the RESTful service.

Also, this instance of the express application is imported to the server file to start the web server and listened to port number 3000.

2. morgan module

Morgan is the HTTP logger middleware for Node.js. With the below statement, this logger is mounted onto the express application. This configuration ensures that the HTTP logger is enabled for development environment so that detailed logging will be made for debugging purpose.


3. body-parser module in the express module

The body-parser module is included with the latest express.js module now. This middleware is used to parse the request body attribute before the request is passed on to other handlers. This object exposes various factories to create the middlewares. 

Below statement creates the middleware that parses only the JSON content-type in the request body. After parsing the JSON request body, it creates an object with parsed content and populates the request body attribute with that new object.


Also, the next line in the apps.js adds another body parser middleware which parses only the URL-encoded request bodies and uses the query string library to do so.

app.use(express.urlencoded({extended: false}));

4. cookie-parser module

To parse the Cookie in the request header, the cookie-parser is used. It populates the req.cookies object with the parsed cookies in key-value pair format with cookie names as keys.

The below statement does this parsing and filling the cookie in the express application’s request object.


App Base URI Middleware

You might remember from the Base Application Preparation post that we added the below block of code within the apps.js file. This code is to handle the express application’s base URL http://localhost:3000/. 

What we are doing in this code is, we are adding a middleware to handle the base URI ‘/’ and a handler function. It means that whenever the express application encounters the base URI ‘/’ after the server’s host and port number or the URL, the following callback function will be invoked.

app.get('/', function (req, res) {
     var pkg = require(path.join(__dirname, 'package.json'));
         version: pkg.version,
         status: 'up'

In that callback function, we are reading the package.json file content after resolving it’s location with the use of Node’s path utility module.

Then the name and version attributes are added to the JSON response object along with the status ‘up’ which is to inform the requester that the RESTful service is up and running with the mentioned name and version number.

It’s a more straightforward way to send the response to the requester about the RESTful service’s necessary information and whether it’s up or not. The status attribute may be redundant as the name and version might be more than enough to indicate that service is up. It won’t hurt though.

Catch & Throw 404 Not Found Error

Route handlers will be added to process any URI/route. If anyone of the route handlers does not handle any of the routes, the application would have to through 404 error to inform the requester that the resource is not found in the server.

To throw the 404 not found error, the below code block is added by the express generator to the apps.js.

// catch 404 and forward to error handler
 app.use(function (req, res, next) {

It is a middleware function mounted to the express application. So any request not handled until this code block will be falling through this middleware.

A new error object is created and passed on to the next function which in turn invokes the next middleware in the stack. The final middleware in the stack is the Error Handler which is described below.

Error Handling Middleware

We need to handle any error that may occur in the express application and throw the appropriate error message to the requester.

Below is error handler code that will be at the end of the apps.js file. The error handler will have four parameters to differentiate from other middlewares. 

// error handler
 app.use(function (err, req, res, next) {
     // set locals, only providing error in development
     res.locals.message = err.message;
     res.locals.error ='env') === 'development' ? err : {};

     // render the error page
     res.status(err.status || 500);

         message: res.locals.message,
         error: res.locals.error

This error handler must be added at last after all the app.use(), and routes call to be able to capture and respond when an error occurs with any code before. In this middleware function, the error message and status are prepared and returned as JSON object back to the requester.

Please check out the index page for this Node.js RESTful API development with TDD approach tutorial with all the posts in sequence in one place.

This blog post is an excerpt from the book Building Node.js REST API with TDD approach. Please check out the link for more information.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.