NodeJS has been in the industry for a while now. Due to its asynchronous nature and support of the Chrome V8 engine, it has become widely popular.

NodeJS offers a number of frameworks that come with different libraries, tools, and templates to help developers get around obstacles when creating apps.

Nodejs is probably one of the best JavaScript frameworks to develop a full-stack application. Once you’ve decided to go with Nodejs, the following frameworks and plugins will be handy in developing backend and API services.

Express

Express is one of the most popular web and API development framework for NodeJS. It has been so widely used that almost every Web development project starts with the integration of Express JS.

ExpressJS

There are a bunch of reasons for choosing ExpressJS as the first plugin.

  • Large bundle of features to support all you need in your development tasks
  • Easy routing facility for routing your web requests to the function
  • Provides an organized platform for coding APIs
  • Supported with most of the other supporting libraries and plugins
  • Secured and maintained consistently to keep up with the standards
  • Great community support

In addition to these benefits, the developers of the plugin have also created an easy-to-use project generator. This generator can create a template project to get you off the feet faster.

Setup Project

Let’s set up a project to learn the basics of the express. Make sure you have installed the node on your system. You can refer to this definitive guide for the node installation process.

  1. Create a project folder.
  2. Open it in the terminal.
  3. Install the express, body-parser, cookie-parser, cors, and nodemon.
  4. Add the index.js file to the project.
  5. Add the application start script in the packages.json file with nodemon index.js command.

Packages

  • express: this is our application’s core package which helps us create APIs.
  • body-parser: this is a middleware that parses the incoming data from the API and adds it to the req.body.
  • cookie-parser: this is a middleware that parses the header Cookie and adds it to the req.cookie.
  • cors: this is a middleware that is used to enable the CORS.
  • nodemon: this is used to run our application which will restart the server whenever any file changes.

These are the basic packages required for the express application to make our lives easier. You may need more packages based on your project. Don’t worry about it now, adding packages is just a command away.

Express App

Let’s see the basic application with different APIs

const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");

// initializing the express
const app = express();
const port = 3000;

// adding the middlewares to the app
app.use(bodyParser.json());
app.use(cookieParser());
app.use(cors());

// req: we will use this paramter to get API request details
// res: we will use
app.get("/", (req, res) => {
  return res.send("Hello, World!");
});

app.get("/json", (req, res) => {
  return res.json({ greetings: "Hello, World!" }); // you can also use res.send({})
});

app.get("/path-params/:name", (req, res) => {
  // all the path params will present in req.params object
  const { name } = req.params;
  return res.json({ greetings: `Hello, ${name}!` });
});

app.get("/query-params", (req, res) => {
  // all the query params will present in req.query object
  const { name } = req.query;
  return res.json({ greetings: `Hello, ${name ? name : "Geekflare"}!` });
});

app.post("/post", (req, res) => {
  // data will present in req.body
  const { name } = req.body;
  console.log(req.body);
  return res.json({ greetings: `Hello, ${name ? name : 'Geekflare'}!` });
});

app.listen(port, () => {
  console.log(`App listening on port ${port}`);
});

Start the application with npm start and try out all the APIs that we have written. Read the documentation to learn more about each concept.

Sails

Sails is a full-fledged MVC architecture framework. It uses ExpressJS and SocketIO at its core. Sails.js got popular for its enterprise-grade architecture that allowed faster integration with the database using model objects.

Sails JS framework

Some of the benefits are:

  • Sails.JS comes with a project to immediately generate a project template
  • The folder structure in Sails.JS is extremely well-organized
  • Development of object models and exposing them using frontend is speedy
  • Allows easy integration of middleware for authorization, authentication and pre-processing
  • Comes with built-in support for AWS S3 and GridFS

Project Setup

To create a sailsjs project, we need an npm package called sail. Let’s install it globally with the following command.

npm install sails -g

Go to the directory where you wanna create your project. Now, run the following command to create sailsjs app.

sails new basic-app

A prompt will appear to select the template. Select the Empty option. Wait till it’s done creating the project.

Open the project in your favorite code editor. Run the sails lift command to run the application. Open http://localhost:1337/ URL in your browser to see the application.

If you see the application in the code editor, you will find a lot of folders and files. You can find a detailed explanation of every folder and file, on Sails documentation page. In this tutorial, we will be seeing one api/controllers and config/routes.js.

SailsJS App

Let’s see how to create APIs in sailsjs app. Check the below steps to create an API in sailsjs app.

  1. Add API endpoint to the config/routes.js file.
  2. Create action for the API endpoint using the command sails generate action sample --no-actions2.
  3. Add your API code in the action file that’s generated in step 2.

Routes

The routes.js file will look similar to the following code after you add API endpoints.

module.exports.routes = {
  "GET /": { action: "home" },
  "GET /json": { action: "json" },
  "GET /path-params/:name": { action: "path-params" },
  "GET /query-params": { action: "query-params" },
  "POST /post": { action: "post" },
};

Each API endpoint is pointing to one action. We have to generate those action files with the command mentioned in the previous section. Let’s generate all the action files for the above endpoints.

Actions

We have added 5 endpoints. Let’s check the respective code for each endpoint.

home.js

module.exports = async function home(req, res) {
  return res.send("Hello, World!");
};

json.js

module.exports = async function json(req, res) {
  return res.json({ greetings: "Hello, World!" });
};

path-params.js

module.exports = async function pathParams(req, res) {
  const { name } = req.params;
  return res.json({ greetings: `Hello, ${name}!` });
};

post.js

module.exports = async function post(req, res) {
  const { name } = req.body;
  console.log(req.body);
  return res.json({ greetings: `Hello, ${name ? name : 'Geekflare'}!` });
};

query-params.js

module.exports = async function queryParams(req, res) {
  const { name } = req.query;
  return res.json({ greetins: `Hello, ${name ? name : "Geekflare"}!` });
};

There is another way of writing actions. Read the documentation to learn more about the framework.

Hapi

Hapi framework was initially built to overcome the drawbacks of ExpressJS framework. Walmart sighted these drawbacks while they were preparing for a heavy traffic event.

HapiJS Framework

Hapi.JS is a robust framework to build services and API. It’s known for its stability and reliability.

Project Setup

Let’s create a project to touch the basics of Hapi.JS. We can set up the Hapi project similar to normal NodeJS project. Run the below commands to set up the project.

cd your_project_floder_path
npm init -y                    ## to init node project
npm install @hapi/hapi         ## installing core package to work with Hapi.JS
npm install nodemon            ## to run our application

Create index.js file in the project. Add the start script in the package.json file with nodemon index.js command.

HapiJS App

Check the basic APIs in Hapi below.

const hapi = require("@hapi/hapi");

const app = async () => {
  // initializing the hapi server
  const server = hapi.server({
    port: 3000,
    host: "localhost",
  });

  server.route({
    method: "GET",
    path: "/",
    handler: (request, h) => {
      return "Hello, World!";
    },
  });

  server.route({
    method: "GET",
    path: "/json",
    handler: (request, h) => {
      return { greetings: "Hello, World!" };
    },
  });

  server.route({
    method: "GET",
    path: "/path-params/{name}",
    handler: (request, h) => {
      const name = request.params.name;
      return { greetings: `Hello, ${name}!` };
    },
  });

  server.route({
    method: "GET",
    path: "/query-params",
    handler: (request, h) => {
      const name = request.query.name;
      return { greetings: `Hello, ${name ? name : "Geekflare"}!` };
    },
  });

  server.route({
    method: "POST",
    path: "/post",
    handler: (request, h) => {
      const data = request.payload;
      console.log(data);
      return { greetings: `Hello, ${data.name ? data.name : "Geekflare"}!` };
    },
  });

  // starting the server
  await server.start();
  console.log(`App is running on ${server.info.uri}`);
};

app();

We have added different APIs to learn the basics of Hapi. You can move all the routes into a separate file to make them clean. Go to the documentation to learn more things about Hapi.

Total

Total is a server-side platform that provides a ready-to-use platform to build real-time, chatbot, IoT, eCommerce, REST applications. It also allows premium users to publish their applications on the platform for others to use.

Total JS

The benefits of using Total.JS as a base for your development are:

  • Rapid prototyping abilities
  • Comes a lot of pre-built components that allows faster development
  • Holds a library of applications that can be easily fetched and integrated into your application
  • Module based framework that allows simplifying work distribution in a large project
  • Community Chat
  • Consistently maintained a store of applications that are ready for use

LoopBack

LoopBack is an API development framework that comes integrated with API explorer. The API explorer can be connected easily to client-side applications using readily available LoopbackJS SDKs. The SDKs are available for Android, AngularJS, Angular 2+ as well as iOS applications.

LoopBack is trusted by GoDaddy, Symantec, Bank of America and many more. You will find many examples on their site to create backend API, secure REST API, persist data, etc. And yes, it got built-in API explorer.

Project Setup

Let’s set up the loopback project and see how to create basic APIs with it.

Run the following command to install the loopback CLI.

npm install -g @loopback/cli

Run the below command to start the project set-up.

lb4 app

Answer all the questions in the terminal. You can answer the questions based on your preference.

Open the app in your favorite code editor and run it with npm start command. Go to http://localhost/ to check the loopback app.

LoopBack App

If you check inside the src folder, there will be a controllers. This is the place where we will add controllers which will contain our APIs.

We have to use the following command to create controllers in loopback.

lb4 controller

Check the different APIs below. We have added multiple APIs to the controller.

import {get, param, post, requestBody} from '@loopback/rest';

interface Response {
  greetings: string;
}

export class GeekflareController {
  @get('/hello')
  home(): string {
    return 'Hello, World!';
  }

  @get('/json')
  json(): Response {
    return {greetings: 'Hello, World!'};
  }

  // accessing path param using @param decorator
  @get('/path-params/{name}')
  pathParams(@param.path.string('name') name: string): Response {
    return {greetings: `Hello, ${name}!`};
  }

  @get('/query-params')
  queryParams(@param.query.string('name') name: string): Response {
    return {greetings: `Hello, ${name ? name : "Geekflare"}!`};
  }

  // accessing path param using @requestBody decorator
  @post('/post')
  postMethod(@requestBody() data: any): Response {
    console.log(data);
    const {name} = data;
    return {greetings: `Hello, ${name ? name : 'Geekflare'}!`};
  }
}

We have seen how to create APIs and access different things required for the basics of REST APIs. There is lot more than this in the LoopBack framework. Their documentation is the right place to dive deep into the framework.

Meteor

Meteor is a complete web development and API creation solution with an incredible design at its core. Meteor is a framework that is used for rapid application building. Meteor architecture allows you to execute code on the frontend as well as backend without having to re-write the code.

Meteor Framework

This improves the development speed by a great extent. Significant benefits of using Meteor are:

  • Hybrid application development framework
  • With a single code base, you can build a desktop app, web app as well as a mobile application
  • It comes with a tightly coupled frontend which helps in reducing your code footprint
  • Highly extensible with a range of plugins
  • Supports various frontend templating frameworks
  • Supports hot code push which allows eradicating the need for updating mobile applications

Restify

Build a production-ready semantically correct RESTfull web service with Restify.

It uses only relevant Express JS modules which make the codebase lighter compared to other frameworks. Trusted by Netflix, Pinterest, Joyent, etc. – you won’t go wrong in choosing them.

Project Setup

Let’s set up the restify project and see how to write basic APIs. Run the following commands to create a new restify project.

Before continuing, make sure you have node with version 11. Restify doesn’t support the latest versions of node.

cd your_project_folder
npm init -y             ## initializing node project
npm i restify           ## installing core package
npm i restify-plugins   ## to add some parsing middlewares to our application
npm i nodemon           ## to run our application

After installing all the packages, add the start script in the package.json file with nodemon index.js command. Don’t forget to add index.js file to the project.

Restify App

Let’s create some APIs to learn the basics.

const restify = require("restify");
const restifyPlugins = require("restify-plugins");

function home(req, res, next) {
  res.send("Hello, World!");
  next();
}

function json(req, res, next) {
  res.json({ greetings: "Hello, World!" }); // you can also use req.send(JSONData)
  next();
}

function pathParams(req, res, next) {
  const { name } = req.params;
  res.json({ greetings: `Hello, ${name}!` });
  next();
}

function queryParams(req, res, next) {
  const { name } = req.query;
  res.json({ greetings: `Hello, ${name ? name : "Geekflare"}!` });
  next();
}

function post(req, res, next) {
  const data = req.body;
  console.log(data);
  res.json({ greetings: `Hello, ${data.name ? data.name : "Geekflare"}!` });
  next();
}

// creating restify server
const server = restify.createServer();

// adding parsing middlewares
server.use(restifyPlugins.jsonBodyParser({ mapParams: true }));
server.use(restifyPlugins.queryParser({ mapParams: true }));

// adding routes
server.get("/", home);
server.get("/json", json);
server.get("/path-params/:name", pathParams);
server.get("/query-params", queryParams);
server.post("/post", post);

// starting the app
server.listen(3000, function () {
  console.log(`App is running at ${server.url}`);
});

Check out the restify documentation to learn more about the framework.

Koa

Koa primarily leverages code generators to allow developers to speed up their development. It comes with various middlewares and plugins to help you manage sessions, request, cookies as well as data transactions.

KoaJS

The same team behind Express designs koa. It works with Nodejs 7.6+ and has a lot of examples for you to get it started.

Project Setup

Let’s set up the koa project with the following commands

cd your_project_folder
npm init -y            ## initializing the node project
npm i koa              ## core koa package
npm i koa-route        ## route package for handling API routes
npm i koa-bodyparser   ## parser package to parse the request body
npm i nodemon          ## to run 

Koa App

Creating APIs with koa is straightforward similar to other frameworks that we have seen earlier. Let’s look at the code.

const koa = require("koa");
const route = require("koa-route");
const bodyParser = require("koa-bodyparser");

const app = new koa();

const home = async (ctx) => {
  ctx.body = "Hello, World!";
};

const json = async (ctx) => {
  ctx.body = { greetings: "Hello, World!" };
};

// all path parameters will will pased to the function with the same name that's provided in the route
const pathParams = async (ctx, name) => {
  ctx.body = { greetings: `Hello, ${name}!` };
};

const queryParams = async (ctx) => {
  const name = ctx.query.name;
  ctx.body = { greetings: `Hello, ${name ? name : "Geekflare"}!` };
};

const post = async (ctx) => {
  const {
    body: { name },
  } = ctx.request;
  ctx.body = { greetings: `Hello, ${name ? name : "Geekflare"}!` };
};

app.use(bodyParser());

app.use(route.get("/", home));
app.use(route.get("/json", json));
app.use(route.get("/path-params/:name", pathParams));
app.use(route.get("/query-params", queryParams));
app.use(route.post("/post", post));

app.listen(3000);

You can start exploring the koa docs now.

Nest

nest

Nest is a framework for building server-side node applications. It uses express under the hood for the HTTP server. And we can configure it with Fastify as well.

It supports TypeScript and is built using OOP concepts, Functional Programming, and Functional Reactive Programming. Let’s create a project in it and see how to write basic APIs.

Project Setup

Run the following commands to create the project.

npm i -g @nestjs/cli                ## installing nest CLI globally
nest new your_project_name          ## creating a project with nest CLI

Nest App

In the application src folder, there are some files. The app.controller.ts is the file where we will include APIs now. Remember we are only going to see how to write basic applications.

Let’s have a look at different basic APIs which will show different concepts of APIs.

import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
import { AppService } from './app.service';

export interface IResponse {
  greetings: string;
}

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('/')
  home(): string {
    return 'Hello, World!';
  }

  @Get('/json')
  json(): IResponse {
    return { greetings: 'Hello, World!' };
  }

  @Get('/path-params/:name')
  pathParams(@Param() params): IResponse {
    const { name } = params;
    return { greetings: `Hello, ${name}!` };
  }

  @Get('/query-params')
  queryParams(@Query() params): IResponse {
    const { name } = params;
    return { greetings: `Hello, ${name ? name : 'Geekflare'}!` };
  }

  @Post('/post')
  post(@Body() body): IResponse {
    const { name } = body;
    return { greetings: `Hello, ${name ? name : 'Geekflare'}!` };
  }
}

Run the application and check all the APIs. You can also write these APIs in the service layer and access them in the controller.

Go to the docs of nest for more learning and understand the framework.

Fastify

Fastify

Fastify is another framework in the NodeJS framework family. As the name suggests, it claims it’s the one of fastest NodeJS frameworks out there. Let’s see some of the core of the framework.

  • Fast and Highly performant. It claims that it can process up to 30K requests per second based on the code complexity.
  • TypeScript friendly.
  • Developer friendly with expressive API for quick development.
  • It comes with a built-in logger. It uses Pino (NodeJS logger).

Project Setup

Let’s set up fastify project to learn the basics of API development. Running the following commands will set up a new fastify project for you.

npm install --global fastify-cli   ## installing fastify CLI
fastify generate project_name      ## creating project with fastify CLI

Fastify App

Fasitfy CLI generated project for us. We are currently worried about only writing APIs. To write new APIs, open routes/root.js file. Add the following APIs in the file.

module.exports = async function (fastify, opts) {
  fastify.get("/", async function (request, reply) {
    return "Hello, World!";
  });

  fastify.get("/json", async function (request, reply) {
    return { greetings: "Hello, World!" };
  });

  fastify.get("/path-params/:name", async function (request, reply) {
    const { name } = request.params;
    return { greetings: `Hello, ${name}!` };
  });

  fastify.get("/query-params", async function (request, reply) {
    const { name } = request.query;
    return { greetings: `Hello, ${name ? name : "Geekflare"}!` };
  });

  fastify.post("/post", async function (request, reply) {
    const { name } = request.body;
    return { greetings: `Hello, ${name ? name : "Geekflare"}!` };
  });
};

Start the application and test all the APIs. These are the basics to write the APIs. Go to the fastify docs to learn more about the framework.

tinyhttp

tinyhttp is a lightweight and express-like JS framework. It comes with a built-in logger, JWT, and CORS middleware. Let’s set up a tiny project and learn the basics of it.

tiny

Project Setup

Run the following commands to set up the tinyhttp project.

cd you_project_folder
npm init -y
npm i @tinyhttp/app     ## core tinyhttp package
npm i milliparsec       ## to parse the request data and add it to request object to body key
npm i nodemon           ## to run our application which will restart automatically whenever files changes

We need to do one more thing. Add type key with value module to the package.json file. We are adding it because tinyhttp doesn’t support require, we need to use import statements instead.

tinyhttp App

The API of tinyhttp looks almost similar to express app. Let’s check the different APIs in it.

import { App } from "@tinyhttp/app";
import { json } from "milliparsec";

const port = 3000;
const app = new App();

app.use(json());

// req: we will use this paramter to get API request details
// res: we will use
app.get("/", (req, res) => {
  res.send("Hello, World!");
});

app.get("/json", (req, res) => {
  res.json({ greetings: "Hello, World!" }); // you can also use res.send({})
});

app.get("/path-params/:name", (req, res) => {
  // all the path params will present in req.params object
  const { name } = req.params;
  res.json({ greetings: `Hello, ${name}!` });
});

app.get("/query-params", (req, res) => {
  // all the query params will present in req.query object
  const { name } = req.query;
  res.json({ greetings: `Hello, ${name ? name : "Geekflare"}!` });
});

app.post("/post", (req, res) => {
  // data will present in req.body
  const { name } = req.body;
  res.json({ greetings: `Hello, ${name ? name : "Geekflare"}!` });
});

app.listen(port, () => {
  console.log(`App running on port ${port}`);
});

You can learn more about the framework in their tiny docs.

SocketIO

SocketIO

SocketIO is a web-socket framework that is available for multiple programming languages.

In NodeJS, SocketIO allows the building of web socket applications like chatbots, score tickers, dashboard APIs and others. SocketIO has significant benefits over the conventional NodeJS web socket library.

  • Support for custom URL routing for web sockets
  • Auto-generated identifiers for every socket
  • Easy management of socket rooms to broadcast data
  • Easier integration with Express JS
  • Supports clustering with Redis
  • Support for socket authentication with an additional plugin – socketio-auth
  • Inbuilt fallback HTTP protocol based handling for a server which does not support HTTP 1.1

Conclusion

People are using NodeJS widely across their projects. As a result, we have various frameworks to choose from. If you see the frameworks, most of them have similar APIs. So, if you have good knowledge of NodeJS and any framework, that’s more than enough to start with any other NodeJS framework.

Developing applications is not easy because of these frameworks. Make good use of the frameworks that you like and keep exploring others.

You may also explore some Node.js Packages to debug, write and manage their code efficiently.

Happy Coding 🙂