DEV Community

Cover image for Best NodeJs Frameworks for Backend development in 2024
alakkadshaw
alakkadshaw

Posted on • Originally published at metered.ca

Best NodeJs Frameworks for Backend development in 2024

In this article we are going to look at the best NodeJs frameworks for 2024  development

We are going to take a look at 4 of the Most popular backend frameworks for development. These are

  • Express JS

  • Nest JS

  • Koa JS

  • Fastify

We are going to take a look at each of these frameworks including

  1. Pros

  2. Cons

  3. Best For

  4. Real Life Apps (Examples)

  5. A Coding example

Image description

Express JS

(63,000 GitHub ⭐, 22,298,401 NPM installs)

Express Js is a lightweight and flexible node js framework that is by far the most famous and industry standared for building node js web applications

Express Js does not provide any magic and that is one of its core features.

Pros of Express JS

1.  Simple and beginner friendly: Express Js is known for being simple and easy to use. It offers straightforward approach to  server side development.

Being simple it is quite easy to get up and running with express and it makes web development faster and easier.

2. Flexibility: Express is un opinionated and thus offers a lot of flexibility, this lets develpoers build apps as they see fit.

Express JS has a lot of community support and middleware options.

3. Performance: Express JS has been designed with performance in mind from the ground up. It has minimun system overhead and gives maximum performance with minimum resources.

4. Middleware and community support: Express Js is the most popular Nodejs server side framework there is.  There is lots of community support and lots and lots of middleware available for different stuff you want to do on the server side

5. Routing Middleware: Express JS has an awesome routing middleware API that supports dynamic URL as well as static URL. You can use these features to build restful API services and apps

Cons of Express Js

1. Less Structured:

It is less structured than other alternatives because of its un opinionated nature. If you are building a large project than expertise is required to build the back end software. Otherwise the project could go haywire. Opionioned frameworks provide a structure to build upon

2. Over reliance on Middleware:

Express JS relies a lot on different types of middleware to deliver different features on the server. This could become cumbersome if you are using a lot of middleware that is built and maintained by third party developers

3. Learning curve required for building large scale apps

express JS is a server side framewwork that can be used to build really large scale apps and is a lot more flexible and some other frameworks out there. You can also push the envelope in terms of development flexibility with express but for this you need developers well versed in express js that requires a learning curve.

Best For

1. Rapid Prototyping

Express Js you can rapidly build a MVC to show off to potential customers or VCs because it is lightweight and does not require a lot of setup to function

2. API development

Express JS has a robust routing mechanism and middleware support which makes it ideal for building RESTful APIs that can be used by client side applications

3. Single Page Applications

You can easily server static files and build APIs that can be used to create Single Page applications. Express JS also works best with front-end frameworks as well such as Angular and React

4. Microservices

Express JS is a lightweight framework and given its nature it is best suitred for building small services that requires few resources in a larger microservices architecture

Real Life Apps that have been built with Express JS

  1. LinkedIn

  2. Uber

  3. Netflix

Real life coding example

  1. Creating a new directory express-test

  2. cd into it and initalize a new project

  3. Creating a simple express js server

mkdir express-test
cd express-test
npm init -y
npm install express
Enter fullscreen mode Exit fullscreen mode
const express = require('express');
const app = express();
const PORT = 3000;

// Adding Middleware in order to parse JSON
app.use(express.json());

// Defining a root route
app.get('/', (req, res) => {
  res.send('Hello, World!');
});

// Define a sample /about route
app.get('/about', (req, res) => {
  res.send('I am an express jS app');
});

// Starting the server and listning to port 3000
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Metered TURN servers

Metered TURN servers

  1. Global Geo-Location targeting: Automatically directs traffic to the nearest servers, for lowest possible latency and highest quality performance. less than 50 ms latency anywhere around the world

  2. Servers in 12 Regions of the world: Toronto, Miami, San Francisco, Amsterdam, London, Frankfurt, Bangalore, Singapore,Sydney, Seoul

  3. Low Latency: less than 50 ms latency, anywhere across the world.

  4. Cost-Effective: pay-as-you-go pricing with bandwidth and volume discounts available.

  5. Easy Administration: Get usage logs, emails when accounts reach threshold limits, billing records and email and phone support.

  6. Standards Compliant: Conforms to RFCs 5389, 5769, 5780, 5766, 6062, 6156, 5245, 5768, 6336, 6544, 5928 over UDP, TCP, TLS, and DTLS.

  7. Multi‑Tenancy: Create multiple credentials and separate the usage by customer, or different apps. Get Usage logs, billing records and threshold alerts.

  8. Enterprise Reliability: 99.999% Uptime with SLA.

  9. Enterprise Scale: With no limit on concurrent traffic or total traffic. Metered TURN Servers provide Enterprise Scalability

  10. 50 GB/mo Free: Get 50 GB every month free TURN server usage with the Free Plan

  11. Runs on port 80 and 443

  12. Support TURNS + SSL to allow connections through deep packet inspection firewalls.

  13. Support STUN

  14. Supports both TCP and UDP

Image description

Nest JS

( 62,800  GitHub ⭐, 2,238,001 NPM installs)

Nest JS is a framework built with elements of Object Oriented programming, functional programming and Functional reactive programming

It is built with typescript and offers a solid foundation for building web apps that are highly reliable, testable and scalable.

You can also create apps with Nest Js that are loosely coupled, so that you can debug and parts of the application as the need arises

Pros of Nest Js

1. Strong Architecture:

Nest Js is strongly inspired by AngularJS, if you are familier with Angular on the front-end than you can easily become up and running with Nest Js. It has modules, services, controllers just like Angular and that makes it easier to manage in large and complex projects. Nest JS also includes dependency injection, which is a featuers that largely simplifies development of large scale applications

2. TypeScript Based

It is based on TypeScript which berings with it benefits of using TypeScript such as strong typing, Object Oriented programming and that leads to good quality code and better developer productivity

3. Extensive Eco System

Nest JS works seamlessly with other libraries and tools such as GraphQL, websockets and micro services. Thus it offers a large eco system for developers to work with

Cons of Nest JS

1. Steep learning Curve

For develpors that are not familiar with Angular and TypeScript this could involve a steep learning curve as Nest JS is basically Angular on the server side

2. large overhead for smaller projects

If you are building a small project or a MVC just as a proof of concept, using nest js could involve a lot of unnecessary setup  and overhead. For these projects choosing express js or fastify ot koa js would be a better option

3. Less flexible due to Opioninated nature and rigid choices

While being opioned gives you a foundation to biuild large scale apps and ability to easily manage prioject across large teams. It also brings with it rigidity and lack of flexibility when building apps

Best For

1. Enterprise level apps

Nest Js is a popular choice in enterprises because of its structured and opionioned approch to software development which is liked by most corporations. This is because it is helpful when building the project across large teams and helps properly manage treams

2. Application requiring a structured approch

If you have an application that has a structured approch to development with well defined features that need to be build out in its lifetime and without a lot of uncertainities then you would benefit from the Nest JS framework

3. Full Stack development with Angular

Developers that love working with Angular on the front end would also appriciate it when developing apps on the back end.  Full stack developers that love working with Angular would love to with Nest JS

Real Life Apps

Coding example

step 1

Creating a new project directory and cd into it then initalize a new project and name it nest-test

npm i -g @nestjs/cli
nest new nest-test
cd nest-test
Enter fullscreen mode Exit fullscreen mode

step 2

Generate a controller called app  just as you do in your angular application

nest generate controller app
Enter fullscreen mode Exit fullscreen mode

now edit the app.controller.ts file to return a hello from nestjs  message

import { Controller, Get } from '@nestjs/common';

@Controller()
export class AppController {
  @Get()
  getHello(): string {
    return 'Hello from nestjs !';
  }
}
Enter fullscreen mode Exit fullscreen mode

step 3

You can also create a service here similar to a angular application. we will call this service app.service

nest generate service app
Enter fullscreen mode Exit fullscreen mode

edit the app.service.ts file

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello from Nest Js Service!';
  }
}
Enter fullscreen mode Exit fullscreen mode

**

step 4**

Modify the app.controller.ts file to use the app.service

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

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

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}
Enter fullscreen mode Exit fullscreen mode

**

step 5**

Start the server

npm run start
Enter fullscreen mode Exit fullscreen mode

your nest js server will run on localhost:// 3000 where you can see "Hello from nest js service" in the root path.

Image description

Koa Js (34,000 GitHub ⭐, 1,120,776 NPM installs)

Koa Js is a new framework built by creators of Express JS. It is a smaller, expressive and roburst framework.

You can build API and Apps with Koa Js. It aims to be a modern framework with newer technologies.

It uses new technologies like async functions, and drops callbacks which greatly increases error handling

Like Express Js Koa does not have any middleware built in, but there are third party developers who can build middleware for Koa Js

Pros of Koa Js

1. Simplicity and minimalism

Koa is known for being minimal and has a barebone framework that can less resource intensive and can be used to build large scale API and web applications

2. Improved Error Handling

Koa uttilizes newer javascript features such as async and await thus imporving upon the express js callback features. This imporves error handling and make the code simpler and easier to read

3. Cleaner and More readable Code

You are able to write cleaner code and avoid the callbacks that you have to do in the express js thus gettign much more cleaner and readable code

4. Highly Customizable

With koa you get a basic framework and then you can add middleware for features that you need. So you get the features that you need and drop the features that you do not need. This makes the application lighter and customizable as well

5. Modern Foundation

Koa JS id built with modern JS concepts and is future proofc hoice for developers looking to leverage latest JavaScript features

Cons of Koa JS

1. Smaller Ecosystem

Compared to express js the Koa ecosystem is smaller in nature. While Koa is growing in popularity it might take some years before it becomes more popular or it might never become as popular as express js. Thus more middleware and features might not be available with koa js

2. Has some learning curve

As Koa Js uses modern javascript language features it will require some learning for developers who might not be well versed in newer JavaScript language features and might feel comfortable with older features.

3. Less popular and hence less support

As I have already mentioned the Koa JS ha a much smaller ecosystem and developers using it than express hense there is less support for it as well. There are fewer stack overflow questions for it and fewer people talking about it than express js

Best For

1. Modern Web Applications

Koa is best suited for developers who are looking to leverage async and await features of javascript

2. Custom Web services

Koa is very lightweight hence if you are building custom web services, you can do that by installing only the middleware that you need and avoid the bloat. Thus achiving customization without unnecessary features

3. APIs that require advanced error handling

Koa has awesome error handling functionality and thus this makes it an excellant choice for developers looking to built error

Simple Coding Example

Create a new directory and name it koa-test and then cd into it then initializa a new application and create a koa js server like

const Koa = require('koa');
const Router = require('@koa/router');

const app = new Koa();
const router = new Router();

// Logger middleware
app.use(async (ctx, next) => {
    const start = Date.now();
    await next();
    const ms = Date.now() - start;
    console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
});

// Response middleware
app.use(async ctx => {
    ctx.body = 'Hello World';
});

// Define a route
router.get('/hello', async (ctx) => {
    ctx.body = 'Hello, Koa!';
});

// Use the router
app.use(router.routes()).use(router.allowedMethods());

// Start the server
app.listen(3000, () => {
    console.log('Server running on http://localhost:3000');
});
Enter fullscreen mode Exit fullscreen mode

Image description

Need Chat API for your website or app

DeadSimpleChat is an Chat API provider

  • Add Scalable Chat to your app in minutes

  • 10 Million Online Concurrent users

  • 99.999% Uptime

  • Moderation features

  • 1-1 Chat

  • Group Chat

  • Fully Customizable

  • Chat API and SDK

  • Pre-Built Chat

Image description

Fastify Js

Fastify is a new Node JS framework designed to be as fast as possible, It aims to be best and the fastest NodeJS framework without compromising too much on the features

Fastify is known for performance and it also has a awesome plug architecture that allows third party devs to build plugins and extend its capabilities

Pros of Fastify

1. High Performance

In applications where performance is a cretical factor in choosing the server side framework, considering fastify is a good choice because it advertises in speed and efficiency

2. Schema based validation

In Fastify there is Schema based validation,which makes it fast and results in consistent data handling.  It uses JSON schema internally to validate routes.

3. Extensible through Plugins

You can entend the framework with plugins and entend its functionality while the core functionality is lightweight

4. Works with Async Operations

You can easily write async await with fastify it fuly supports async/await functionality out of the box

5. Newer technologies

It supports newer technologies like better typescript support, async await support and others

Cons of Fastify

1. Smaller community and ecosystem

Compared to more established frameworks like Express JS. Fastify is a realtively new player and has a smaller community that means fewer stack overflow questions and fewer third party middleware built for fastify

2. Coding overhead for smaller applications

For smaller apps and MVC or demo apps, that do not benefit much from fastify fast performance it would be better to go with express js and this might be a learning curve as well as coding overhead working with fastify.

Best For

  1. Creating High performance APIs

When you have need for speed and fast performance then Fastify can handle a lot of requests fast and it is a good choice for building high performance APIs

2. Microservices

It has low overhead, fast boot time and support for async operations these featues make it a good choice for creating microservices

3. Real Time Applications

Apps that are real time in nature such as chat xould benefit from fastify fast performance.

Simple Coding Example

In this we are going to create a fastify server and start it on port 3000 then we are going to do JSON schema validation for the query parameters

This will demonstrate the fastify fast performance capabilities and support for schema based validation that is helpful for developer productivity and also demonstrate that newer javascript features work well with fastify

const fastify = require('fastify')({ logger: true });

// Declare a route with JSON schema validation
fastify.route({
  method: 'GET',
  url: '/index',
  schema: {
    querystring: {
      name: { type: 'string' },
      excitement: { type: 'integer' }
    },
    response: {
      200: {
        type: 'object',
        properties: {
          greeting: { type: 'string' }
        }
      }
    }
  },
  handler: async (request, reply) => {
    const { name, excitement = 1 } = request.query;
    const greeting = `Hello, ${name}${'!'.repeat(excitement)}`;
    reply.send({ Hello world });
  }
});

// starting the server!
const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
    fastify.log.info(`server listening on ${fastify.server.address().port}`);
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};
start();
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article we learned about some of the best server side frameworks that are in use today.

And you can choose amoung these frameworks what ever best suits your use case. Express JS to fastify all of them are awesome framework and are fun to work with

Let me know if you liked the article

Top comments (3)

Collapse
 
restdbjones profile image
Jbee - codehooks.io

Good writeup 👍

Collapse
 
alakkadshaw profile image
alakkadshaw

Thanks for reading. Let me know if you liked the article

Collapse
 
johnmunsch profile image
John Munsch

I can't help but feel that you blew right by one of the biggest cons for Express today. It's not exactly what you would call "in active development"; it's last releases of version four and five were in October 2022. As I write this that's 18 months without even a minor release for a major back-end framework.

100+ open issues and around 70 open pull requests reinforce the idea of a project that isn't getting the love that it needs to be something you should build your projects around.