ExpressJS vs NestJS | Battle Between Backend Frameworks

July 14, 2022 • 1627 Views • 15 min read

author photo

Tetiana Stoyko

CTO & Co-Founder

Today we are considering two partly different backend frameworks, related to Node.js. Such software is usually used to develop web or mobile applications. In fact, both of them can be used for large- and small-scale projects, however, there are a few "buts", worth mentioning.

Actually, the comparison between ExpressJS vs NestJS, as well as the discussion about which one is better is still in progress. Both of them are among the most popular frameworks. So what is the difference? Let's find out.

What is ExpressJS?

ExpressJS, also known as Express, is one of the oldest Node.js environment frameworks. It was developed more than 10 years ago. Its popularity can be explained by the fact, that it is easy to learn how to use Express, as well as the components and software it uses. For instance, it is a JavaScript-based framework, that is able to use or cooperate with other similar libraries and frameworks.

ExpressJS Features

First of all, Express is an unopinionated framework. It means, that there are no strict rules or design patterns, that must be followed. Conversely, it allows a full-fledged modification and development with the tools and components, that meets all the developer's requirements. In other words, the developer chooses the tech stack according to its own needs.

As was mentioned before, it is using NodeJS. Therefore, it is a great decision to choose Express in case, if you will need to handle a lot of input and output data like notifications or requests. Thanks to the Node.js environment, it can facilitate non-blocking I/O operations. As a result, it is possible to process multiple requests simultaneously, which highly speeds up the overall working process.

The ExpressJS and JavaScript developers community is large. It regularly produces dozens of content related to the development of products, based on these technologies. Also, it is a great source of hints and advice. If there is something unclear in the official documentation, the developer can easily find a more detailed explanation or even assistance from others. There are lots of free-to-use add-ons and additional content, that can be used to extend the functionality too.

Using the JavaScript language for server-side web framework is also a great bonus. Usually, server-side web frameworks are based on programming languages, that differ from the ones, that are used for the front-end. In the case of Express, it can be the same language. Therefore, it will be much easier for the developer to code and test the code. Also, it helps to optimize the working process by enabling server-side rendering.

Eventually, Express is a great choice for developer, who is considering developing the application by themselves. This framework is easy enough to be sealed with by a single person. However, it can become a challenge if another person will join the development process because it is unopinionated and each developer sets its own rules, so it can take some time to understand the code logic.

Express Middleware

In addition to the foregoing, ExpressJS allows using middleware. In simple words, it is a linkage between system components; an additional way of communication between separate or distributed systems. It can be used for various purposes, however, one of the most common types of middleware is the authentication one. Usually, in Express we can chain handler functions in an endpoint any way we want. The result will look like this:

app.<METHOD>(<PATH>, <HANDLER>, <HANDLER...>)
  • app - is the Express app instance;
  • METHOD - is the needed HTTP method;
  • PATH - is the route URL link to the specific endpoint;
  • HANDLER - is obviously the handler function. The number of these functions can vary, as well as their position, which depends on the specific order. Mostly, this order is arranged and the functions are called due to this order. Also, there is a controller handler(usually, it is the last one). Rest handlers are middleware.

The authentication middleware for the ExpressJS on the code level looks like this:

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const token = req.headers.authorization.split(' ')[1];
    const decodedToken = jwt.verify(token, 'TOKEN_SECRET');
    
    return next();
  } catch {
    return res.sendStatus(401);
  }
};

In case one of the handlers causes the unhandled error, then the error handler is used:

app.use((err, req, res, next) => {
  return res.status(500).send('Something went wrong!');
});

What is NestJS?

As a matter of fact, it is possible to say that NestJS is built on top of ExpressJS. Both of them have a similar purpose and provide comparable functions. Also, Nest as well as Express is a framework for NodeJS and can be based on JavaScript. However, there are a lot of differences too. Additionally, NestJS can use Express or Fastify under the hood.

Franky speaking, Nest is rapidly growing in popularity, becoming the framework of choice. In fact, it is a great alternative worth considering. Its main advantage, comparing ExpressJS vs NestJS, is the out-of-the-box solutions provided.

NestJS Features

First of all, Nest is opinionated, meaning that there are strict rules to follow. On the one hand, it seems to be rather a drawback, than an advantage, giving less choice for developers. However, this helps them to switch to another project, knowing that the developer will understand the logic of the application structure. Because all of these preset rules are common for all projects, it easy to understand the code.

Additionally, Nest can be built using TypeScript or JavaSript. The reason is simple - NestJS is Angular-based. Using TypeScript allows using the "type" feature, which is a great tool for developing scalable applications. Besides, there are decorators among TypeScripts features. Decorators allow treating third-party modules and programs as native. As a result, the program can easier deal with the incoming data.

The most important NestJS advantage is that it uses Command Line Interface(CLI). It helps to improve the performance and to avoid writing additional code, for example, the one for unit testing. The Nest CLI also goes with the Jest testing environment. It helps to partly automate the unit testing process by enabling the auto-generated testing bed code features as well.

Also, NestJS follows Model View Controller(MVC) architecture. It results in additional code structurization as well as the possibility to use various add-ons, modules, or components, extending the functionality and code clarity. Among various extensions, Nest supports microservices. Therefore, it is possible to build not only a monolithic application structure but to use the microservices architecture as well. Consequently, the choice for developers is even bigger than in the case of Express.

Frankly, in the case of the development of a scalable application or a medium one, Nest provides much more features, including the ones, that are provided by the ExpressJS. For instance, previously mentioned middleware is also possible in Nest. Nonetheless, it slightly differs.

NestJS Middleware Types

NestJS middleware has various middleware types, each of which has its own usage purpose. Among them are:

  • Ordinary middleware, which is just common middleware.
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Log before next middleware.');
    next();
  }
}
  • Exception filters, that are similar to the error handlers in ExpressJS, and process all the unhandled exceptions across the app.
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    response
      .sendStatus(status);
  }
}
  • Pipes are used for validation and transformation of request data:
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';

@Injectable()
export class ValidationPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    return value;
  }
}
@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
  return `Id: ${id}`;
}
  • Guards. This middleware determines whether to give access to the resource, or not. Mostly, the most common subtypes of this middleware are authentication and role guards.
import {
Injectable,
CanActivate,
ExecutionContext,
UnauthorizedException
} from '@nestjs/common';
import APP_CONFIG from '../../configs/app.config';
import jwt = require('jsonwebtoken');
import { Reflector } from '@nestjs/core';

@Injectable()
export class AuthGuard implements CanActivate {
constructor(private readonly reflector: Reflector) { }

async canActivate(
  context: ExecutionContext,
): Promise<boolean> {
  try {
    const request = context.switchToHttp().getRequest();
    if (!request.headers.authorization) {
      throw new UnauthorizedException();
    }

    const {
      data: { id },
    } = jwt.verify(request.headers.authorization, APP_CONFIG.SECRET);
    if (!id) {
      return false;
    }

    return true;
  } catch (err) {
    throw new UnauthorizedException();
  }
}
}

The variety of middleware helps to make the code cleaner and to easily identify the type of communication inside or between the systems.

ExpressJS vs NestJS Comparison

Let's start with the similarities. Obviously, both server-side web frameworks belong to the Node.js environment, no need to mention that they are also backend frameworks. Both of them are able to use JavaScript as the main programming language. Each of them allows database access, as well as other pleasant add-ons, that can simplify the work of the developer, and increase the development speed.

Clearly, there are some differences as well. For instance, unlike Express.js, Nest.js has a wide range of out-of-box solutions including gateways for sockets, lifecycle events that give control over application workflow, support for microservices style development, and easy-to-use swagger decorators, and many more. Eventually, it is possible to say that both backend frameworks are great. Nonetheless, if you are looking for a framework for a new project, that will be developed from scratch, it would be a better decision to pay attention to NestJS because it supports new innovative software.

All these facts together with detailed and convenient documentation will help to develop a full-fledged product, that will be relevant for a long time thanks to the possibility to integrate new software if needed. Yet, ExpressJS is also an excellent framework, worth considering. It may be partly outdated, however, it has already proven its reliability and utility. A friendly and large community, combined with a long existence and the number of various solutions and supplements developed creates very comfortable conditions for the developers. For example, Express is a part of the MEAN solution stack, so it can be combined with MongoDB, Angular, and Node.js.

End Line

Frankly speaking, it is hard to tell exactly how to choose a JavaScript framework for your initial project due to a large number of features and details that need to be taken into account. Yet, the final decision has to be made by the developers. Nonetheless, we hope that this short article will help to better understand all the pros and cons of these two frameworks.

Here, in Incora, we always care about the quality of the projects we are taking part in. In case you are looking for experienced developers, that eager to start a new project and find new solutions - just contact us and we will take care of the rest.

Share this post

Tags

Tech
Comparison

What’s your impression after reading this?

Love it!

Valuable

Exciting

Unsatisfied

Got no clue where to start? Why don’t we discuss your idea?

Let’s talk!

Contact us

chat photo
privacy policy

© 2015-2024 Incora LLC

offices

Ukrainian office

116, Bohdana Khmel'nyts'koho, Lviv, Lviv Oblast, 79019

USA office

16192 Coastal Hwy, Lewes, DE 19958 USA

follow us

This site uses cookies to improve your user experience.Read our Privacy Policy

Accept