thinkbridge recognized in Gartner’s Market Guide for Digital Technology and Business Consulting Services
Learn More
Market Guide for Digital Technology and Business Consulting Services
Celebrating A Decade Of Innovation
Why thinkbridge is a great place to work?
Market Guide for Digital Technology and Business Consulting Services
Celebrating A Decade Of Innovation
Why thinkbridge is a great place to work?
8 min read

The Best Node.js Framework For Real-Time Chat Applications

Node.js/Fastify/Koa/Express/Strapi/Nest/Backend Development/Backend Engineering/Backend Developers/Software/Software Development/Real-Time Chat Application/Tech/Technology
Want to create a real-time chat application but aren't sure which framwork to use? We did some digging and analyzed several frameworks to determine each one's feasibility. This is what we found.
Written by
Jem Pool Suarez
Published on
April 12, 2024

Let's take a look at the top Node.js frameworks. Each framework has its own strengths and features, but which would be best for creating a simple, real-time chat application? Nowadays, web applications need such features to keep users engaged, so building a real-time chat app is necessary.

Node.js is a great tool for building real-time apps because of its asynchronous and event-driven design. However, even within the Node.js ecosystem, there are many frameworks to choose from. How do you pick the right one for your specific project? It's important to choose the correct Node.js framework for your chat app. Your choice can affect your project's progress, performance, and scalability.

The list of frameworks to be analyzed was taken from the results of the stateofjs 2022 survey.

We have selected the top 5 Backend Frameworks listed as the most used:

  • Express.
  • Nest.
  • Fastify.
  • Strapi.
  • Koa.

Definition of the problem.

We list these requirements to make the problem more complex than a simple to-do. This helps us decide which Node.js frameworks are best for the solution. Then, we analyze each framework based on the information we gather.

Requirements:

Develop an application like a chat room that implements Real-Time Messaging. Users should be able to authenticate themselves. They should also create accounts, log in, and keep their identity during sessions. Messages should be delivered to the recipient in real-time without a manual refresh or page reload. The scope of these requirements does not include application deployment.

Express

Express.js is a popular web application framework for Node.js. It's known for its simplicity and flexibility, making it a go-to choice for building web and mobile applications. Here's a brief overview:

Key Features:

  1. Middleware Support: Express uses middleware functions to handle requests and responses. This enables modular and customizable application design.
  2. Routing: It provides a robust routing system. Defining routes for different HTTP methods and URL patterns is easy.
  3. Template Engines: Express supports various template engines like Pug, EJS, and Handlebars. It's adaptable to other preferences.
  4. HTTP Utility Methods: It simplifies tasks with built-in methods for handling HTTP requests and responses.
  5. JSON Support: Express has built-in support for handling JSON data, making it easy to work with APIs.
  6. Extensibility: Developers can easily integrate third-party modules and packages to extend functionality.
  7. MVC Architecture: While not strictly enforcing MVC, Express supports the separation of concerns. Developers can organize their code in a way that follows the MVC pattern.

Pros:

  1. Lightweight and Minimalistic: Express is designed to be unopinionated and minimal. Developers have the freedom to structure their applications as they see fit.
  2. Widespread Adoption: Being one of the most popular Node.js frameworks, it has a large and active community. There's extensive documentation, tutorials, and third-party modules.
  3. Flexibility: Express doesn't impose a rigid structure. Developers choose libraries and tools based on their project requirements.
  4. Performance: It's known for its fast performance. This capability makes it suitable for both small-scale projects and large-scale applications.
  5. Middleware: The middleware system enables developers to add functionality modularly. Code reusability is inherently promoted.

Cons:

  1. Lack of Opinionation: While flexibility is an advantage, it can also be a drawback for developers who prefer a more opinionated framework with predefined conventions.
  2. Learning Curve: For beginners, the lack of strict guidelines might result in a steeper learning curve compared to more opinionated frameworks.
  3. Boilerplate Code: Since Express is minimalistic, developers might write more boilerplate code for specific features that other frameworks provide out of the box.
  4. Not a Full-Fledged Framework: Express focuses on the web server aspect, and developers often need to choose additional libraries for database interaction, authentication, and other standard features.

Implementation

I chose Angular to make the client and MongoDB for the database. Then, I searched for a library to connect the client and server in real time. Among the most common Real-Time Data Communication techniques are Server-Sent EventsPolling, and Web Sockets. I selected the latter for its bidirectional approach. The most used JavaScript libraries of the previously selected process are WS and Socket.IO. I chose the latter because its repository has more activity and more detailed documentation. I selected the Passport.js library because it is well above similar libraries such as everyauth, Grant, node-jsonwebtoken, CASL, etc., as indicated in its documentation: "Passport has a comprehensive set of over 480 authentication strategies covering social networking, enterprise integration, API services, and more".

In this library, I chose the passport-local method. It's a Passport strategy for logging in and registering new users with a username and password. I picked it because I wanted the server to have a bigger role in the process. Other strategies in the library, like passport-http-bearer, passport-facebook, passport-google-oauth, passport-auth0, etc., mainly rely on a third party for this responsibility. I successfully established communication between the client and server using the mentioned libraries. I didn't encounter any significant problems, so I was able to implement the solution to the problem. There's still room for improvement in the application, the code contains what is necessary to fulfill our desired scope.

Nest

Nest.js is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It makes developing robust, maintainable web applications and APIs more straightforward by incorporating the best practices from other frameworks and languages.

Key Features:

  1. Modularity: Nest.js encourages a modular structure. Developers can organize the code into reusable modules. This promotes a clean and maintainable codebase.
  2. Dependency Injection: Nest.js utilizes dependency injection, making it easy to manage and inject the dependencies of components. This enables modular and testable code.
  3. Express.js Compatibility: Nest.js is built on top of Express.js, a popular web application framework for Node.js. Nest.js applications can still leverage the extensive middleware ecosystem available for Express.
  4. TypeScript Support: Nest.js is written in TypeScript, a superset of JavaScript that adds static typing. This provides developers with improved tooling, type checking, and code quality.
  5. Decorators: Nest.js uses decorators for defining and configuring modules, controllers, services, and more. This helps in writing concise and expressive code.
  6. WebSockets Support: Nest.js has built-in support for WebSockets, enabling real-time communication between the server and clients.
  7. CLI (Command Line Interface): Nest.js provides a powerful CLI for scaffolding and managing projects, making it easier to create components, modules, and more.

Pros:

  1. Scalability: Nest.js is well-suited for small and large applications due to its scalable architecture.
  2. Code Reusability: The modular structure and dependency injection system enables code reusability. It's easier to maintain and extend applications.
  3. TypeScript Benefits: TypeScript brings static typing to Nest.js, improving code quality, providing better tooling, and catching potential errors during development.
  4. Express.js Compatibility: Since Nest.js is built on top of Express.js, it can leverage Express's existing middleware and ecosystem.
  5. Active Community: Nest.js has a growing and dynamic community. There is solid community support. Developers can find various resources and third-party packages easily.

Cons:

  1. Learning Curve: For developers unfamiliar with concepts like decorators, dependency injection, or modular programming, there might be a learning curve when starting with Nest.js.
  2. Opinionated Structure: Nest.js enforces a particular structure and architecture, which might be seen as restrictive by some developers who prefer more flexibility.
  3. Size of the Community Ecosystem: While the community is active, it might not be as extensive as some other frameworks. The availability of specific plugins or extensions could be limited.

Implementation

First, I started reading the documentation and running the suggested basic project. The documentation is very well organized and complete, especially concerning WebSockets, Mongoose Integration, and Authorization.

I had not used this framework before, and my first experiment was to program a server using Angular. At first, I thought that this framework had a stricter architecture than Express. I considered making a folder for the UI layer and another for the business logic and database interaction, which includes controllers and services. However, the documentation recommends organizing each module with their own DTOs and Schemas. So, I decided to follow that approach. This framework is designed to be developed using TypeScript, so I chose to use it despite the challenges. The framework ensures that the style errors be fixed. Although it offers the option to select between any of the three package managers, NPM, Yarn, and pNPM, I opted for the classic NPM.

I implemented the WebSockets logic in the same order as Express. The official documentation says there are two supported WS platforms: socket.io and ws. I looked at the Socket.IO implementation in the documentation because I wanted it to be compatible with the Express project. In that project, I had already used the Socket.IO library for real-time communication with the Angular client. I wanted to use the same client for all the Frameworks on the list. I used the @nestjs/jwt library. Initially, I had in mind to use Passport.js for the authentication logic. However, the documentation presented a more framework-friendly approach using the @nestjs/jwt library, which is described as "JWT utilities module for Nest based on the jsonwebtoken package. This library includes generating and verifying JWT tokens". I used Passport.js in Express mainly for its authentication strategies and the integration as a middleware. Mostly to extract the credentials and the JWT tokens from the client requests. These can be easily handled in Nest by using the JwtModule and passing the credentials to the services that are injected as dependencies. As in Express, use the bcrypt library to hash the password when storing it in the database.

I established the communication flow between the client and server without any problems. I say this because evaluating usability is essential. This particular framework seems to stand out for that.

Fastify

Fastify is a web framework for building efficient and high-performance web applications in Node.js. It is designed to be lightweight, extensible, and easy to use.

Key Features:

  1. Performance-Oriented: Fastify is known for its exceptional performance. It achieves this by focusing on low overhead and fast execution. It's one of the fastest web frameworks for Node.js.
  2. Schema-Based Validation: Fastify uses JSON schema to validate request and response payloads. This helps ensure data consistency and provides a clear contract between the client and the server.
  3. Plugin System: The framework has a robust plugin system that allows developers to modularize their applications. This modularity is achieved by encapsulating functionality into plugins. Code reusability and maintainability are promoted.
  4. Asynchronous: Like many modern Node.js frameworks, Fastify is built to support asynchronous programming. It leverages features like async/await for handling asynchronous operations.
  5. Logging and Monitoring: Fastify includes built-in support for logging and monitoring. Tracking and debugging issues in your application is simple.
  6. HTTP2 and HTTP3 Support: Fastify supports the latest versions of the HTTP protocol, providing the benefits of features like multiplexing, header compression, and more.

Pros:

  1. Performance: Fastify is renowned for its impressive performance, making it an excellent choice for high-throughput applications.
  2. Schema-Based Validation: Using JSON schema for validation enhances the robustness of applications by enforcing a clear structure for input and output data.
  3. Extensibility: The plugin system allows developers to extend and customize the functionality of their applications easily.
  4. Active Community: Fastify has a growing and vibrant community that contributes to plugins, documentation, and support. Developers can find resources and assistance easily.
  5. Asynchronous Support: Using Node.js's asynchronous nature, Fastify handles concurrent requests efficiently.

Cons:

  1. Smaller Ecosystem: While the Fastify ecosystem is growing, it may not be as extensive as some other Node.js frameworks. This might limit the availability of specific plugins or integrations.
  2. Learning Curve: Developers familiar with other frameworks might face a learning curve when transitioning to Fastify due to its unique features and approach.
  3. Less Opinionated: While flexibility is an advantage, the less opinionated framework might require developers to make more project structure and organization decisions.

Implementation

To begin with, I went through the general aspects of the documentation. I then initialized the project using the CLI and went through the structure of the resulting template. After that, within the documentation, I reviewed the three most important aspects of this project: WebSockets, MongoDB integration, and authentication.

Regarding WebSockets, Fastify offers two built-in options:

  • @fastify/websocket: WebSocket support for Fastify. It is built upon wa.
  • fastify-ws: WebSocket integration for Fastify — with support for WebSocket lifecycle hooks instead of a single handler function. It is built upon ws and uws.

The fastify-ws library is not being actively developed. Additionally, the @fastify/websocket library does not offer a built-in method to broadcast messages. It seems necessary to iterate over the WebSocket Server clients to send the message to all clients connected to the conversation. To keep the code as simple as possible and maintain uniformity with previous implementations, I opted to use the external libraries 'fastify-socket.io' and 'socket.io.' With this, the code used was practically reused from the Express project.

The integration with MongoDB, as in the previous frameworks, was through the Mongoose library, which is integrated as in Express.

The authentication methods use the libraries: jsonwebtoken to verify the token's validity concerning the JWT Secret, generate the Access Token and the Refresh Token, and bcrypt to hash the passwords before storing them in the database. Something that becomes evident while solving the first errors is that the number of results from Google searches are less numerous than in Express and Nest. That's a clear indication that this community is still growing. I followed the best practices recommended in the official documentation. I used schemas, decorators, and plugins for this. Schemas helped me validate request objects and responses. The documentation mentioned that using a schema can increase throughput by 10-20%. I registered the fastify-socket.io library as a plugin. I also used decorators to add extra functionality to the reply object. This allowed me to pass user data from the authorization service to the controllers. I also used decorators to define the 'authorize' function. On the other hand, in the authentication process, the services are executed in the preHandler. The controllers in the handler, using the preHandler, are suggested when we need to access the body content in the authentication process.

Strapi

Strapi is an open-source headless content management system (CMS) that provides a flexible and customizable way to manage and deliver content through APIs. It allows developers to build robust, scalable web applications and digital experiences.

Key Features:

  1. Headless CMS: Strapi follows the headless CMS architecture, separating the backend (content management) from the frontend (presentation). This enables developers to use their preferred frontend technologies while benefiting from a robust content management system.
  2. API-First Approach: Strapi is designed with an API-first approach, allowing developers to create APIs easily and use them to deliver content to various channels, such as websites, mobile apps, and more.
  3. Customizable Content Types: Users can define content types and structures to suit specific project requirements. This flexibility makes it suitable for a wide range of applications and industries.
  4. User Authentication and Permissions: Strapi provides built-in user authentication and role-based access control (RBAC), making it easier to manage user roles and permissions for different application parts.
  5. Content Versioning: Strapi supports content versioning, allowing users to track changes made to content over time. This feature is helpful for content auditing and rollback purposes.
  6. Plugin System: The framework offers a plugin system that allows developers to extend functionality easily. A growing ecosystem of community-contributed plugins can be used to enhance Strapi's capabilities.
  7. Database Agnostic: Strapi is database-agnostic, which supports various databases such as MongoDB, PostgreSQL, MySQL, and SQLite. Developers can choose the database that best fits their project requirements.

Pros:

  1. Open Source: Strapi is an open-source project that allows developers to use, modify, and distribute the software according to their needs.
  2. Flexibility: The customizable content types and API-first approach make Strapi suitable for various projects and use cases.
  3. Active Community: Strapi has a growing and dynamic community of developers, which means there is ample documentation, tutorials, and community support available.
  4. Easy to Use: Strapi offers an intuitive admin panel for content management, making it easy for non-technical users.
  5. Scalability: The headless architecture and support for various databases contribute to Strapi's scalability. It's suitable for both small projects and large enterprise applications.

Cons:

  1. Learning Curve: While the admin panel is user-friendly, there might be a learning curve for developers new to Strapi or headless CMS concepts.
  2. Middleware Complexity: In some cases, managing complex middleware configurations may be challenging for developers.
  3. Community-Dependent: As an open-source project, the level of support and updates can depend on the community. However, the growing community is generally seen as a positive aspect.

Implementation

Strapi is a tool for creating CMS and APIs quickly. At first, it didn't seem like a framework for making a Real-Time Chat application because its main focus is managing content and exposing it through APIs. But to evaluate it fairly, I looked at the documentation, especially the parts about WebSockets, MongoDB integration, and authentication.

The first thing I found was that, as stated in the documentation, "Starting from the release of Strapi v4, MongoDB is not supported natively anymore, and no connector is available". Because of compatibility issues between Strapi V4 and the socket.io library, I decided to downgrade to the latest release of V3, which is version "3.6.11". This version worked without any problems. I want to clarify that the reason I used different Node.js frameworks was to compare the client and database in a consistent manner. I also tried to use the socket.io library for WebSocket communication as much as possible.

The documentation is comprehensive, and I needed to consult doubts outside the official forums very few times. Unlike previous frameworks, Strapi offers an admin console in the browser for content management. Although the framework provides APIs to perform actions on users and collections, it is possible to create routes with custom logic to interact with plugins. I took advantage of this feature to define the Login and Signup routes to fit the format used in the Angular client. For authentication, I used the 'jsonwebtoken' library since I needed to customize the content of the tokens.

To connect to the MongoDB database, you just need to assign the right connector and other connection variables. Strapi has a query API to interact with the database. I used the 'socket.io' library to implement the WebSockets. The logic was the same as the previous frameworks. The only difference is how it's initialized. The logic for this library is placed in the bootstrap.js file. According to the documentation, the bootstrap.js file contains an asynchronous bootstrap function that runs before the application starts.

Finally, I could implement the proposed problem as in the previous frameworks. I believe that Strapi is not the appropriate framework for this type of application. That is to say that this type of application can be developed. But, all the functionalities the framework offers by default are being underused. The integrated logic could lead to unnecessary overhead when the application needs to be scaled.

Koa

Koa.js is a lightweight and modern web framework for Node.js, designed by the team behind Express.js. It was created to address some of the shortcomings of Express and to take advantage of newer features in JavaScript, especially the async/await syntax.

Key Features:

  1. Middleware Flow: Koa uses a more modular and expressive approach to middleware. It relies heavily on async functions, making it easy to write and manage asynchronous code.
  2. Async/Await: Koa takes full advantage of ECMAScript 2017 (ES8) features, particularly async/await. Handling asynchronous operations without callbacks is simple.
  3. Lightweight Core: Koa has a small, focused core with many features moved to external middleware. Developers can include only the modules they need for their specific application, keeping the codebase clean and efficient.
  4. Context Object: Koa introduces a context object that encapsulates the request and response objects, providing a cleaner way to interact with the HTTP request and response.
  5. Generators: While newer JavaScript features like async/await are now more prevalent, Koa initially gained attention for using generators to handle middleware. However, this is an older feature, and async/await is the recommended approach.

Pros:

  1. Clean and Readable Code: Koa encourages writing clean and readable code, especially when dealing with asynchronous operations. Using async/await simplifies handling asynchronous code compared to traditional callback-based approaches.
  2. Flexibility: Koa's modular architecture allows developers to choose and use only necessary components. This flexibility can lead to more lightweight and tailored applications.
  3. Modern JavaScript Features: Koa leverages modern ECMAScript features, aligning it with contemporary JavaScript development practices.

Cons:

  1. Learning Curve: Koa simplifies many aspects of web development. However, the heavy use of async/await and the different middleware approaches may create a learning curve for developers more accustomed to traditional callback-based frameworks.
  2. Ecosystem Size: While Koa has a decent ecosystem, it might not be as extensive as Express.js, which has been around for longer and is widely adopted. Finding specific middleware or community support might be a bit more challenging.
  3. Backward Compatibility: Koa 2 introduced some breaking changes compared to Koa 1, which might require modifications to existing codebases when upgrading.

Implementation

As in previous frameworks, I started reading the most relevant aspects of the documentation. From this point, the minimalism appears obvious since the documentation is clear but not extensive. The three most relevant aspects are WebSockets, integration with the MongoDB database and Authorization. I implemented the external libraries Socket.io, Mongoose, and jsonwebtoken, respectively. At this point, it is to be expected that the application has been implemented without significant problems.

Koa seems to be the most similar to Express of all the frameworks discussed so far. However, Koa has a few notable differences. One difference is that it allows us to manage Middlewares with a flow downstream and upstream. This means we can perform actions after the subsequent middleware has finished executing. We can also do post-processing of the response or additional operations based on previous results. Koa is helpful for tasks like timing requests, applying response transformations conditionally, or cleaning resources.

This pattern allows Koa to handle the "before" and "after" aspects of middleware logic in a single function. In the case of our Basic Real-Time Chat Application, I don't think middleware management will make a difference compared to Express. The use of modern JavaScript doesn't have a significant impact either. When comparing this framework to others for our specific problem, we can classify Koa as a more minimal version of Express with a smaller community. If we want to create new features and manage process flow more elegantly, Koa is an exciting option. Koa is flexible. So, you should prioritize organizing the structure and managing middleware, even for common tasks. Project components also need to be linked.

Weekly newsletter
No spam. Just the latest releases and tips, interesting articles, and exclusive interviews in your inbox every week.
Read about our privacy policy.
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Contact us

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Take a step closer to the new way!

Explore creative and new approaches with experts by your side.