Node.js code architecture for scalable projects

Malik Atique
3 min readSep 4, 2022

--

Photo by Mohammad Rahmani on Unsplash

For a Crypto Exchange project, I had to design application architecture for microservices. The project involved many technology stacks therein. However, for core backend APIs, we were using Node.Js. So my main challenge was to find a code architecture for Node.js that is easy to use, scalable, organised and must follow the best coding practices.

I skimmed many open source projects and read articles about the best code structures, but none were captivating. So I decided to build one on top of Express Js. Starting from application bootstrapping, I added features as deemed required like: routing, controller handlers, consistent response, validations, etcetera.

Express.js Code Structure:

Node.Js code directory structure

The complete application is inside the src folder. And the application’s entry point is src/index.js; it will bootstrap the entire application from the src/bootstrap/app.js file.

The src/app directory:

The src/app directory for Node.Js code structure

The app directory contains the business logic of the entire application. It consists of controllers where we handle route requests, middlewares, mongoose models, validations for APIs, and repositories for the core business logic.

Read the documentation of the Joi validations library: https://joi.dev/api

The src/bootstrap directory:

The bootstrap directory is responsible for gracefully starting our application. The app.js file will systematically perform the following tasks;

  • apply middlewares,
  • register Joi validation rules,
  • load mongoose models,
  • establish a connection with the database,
  • third-party service(s) that you might be using in your application.

The src/commands directory:

Soon, I will update this article. Where I will divide the framework’s code base into modules like authentication, email scheduling, notification service, validations, etcetera. The initial structure will be minimal. So you can install modules as per your requirements.

The src/framework directory:

The framework directory contains all the generic code necessary to run the application. It will keep evolving as we add more and more features with version updates.

The src/routes directory:

The route directory contains all the routes for RESTful APIs organised in different files. These routes are bound to controllers.

Soon, I will update this part for the Socket methods as well.

The src/scripts directory:

The script directory contains the test cases for the application. You can write your test cases using Mocha.

Here is the link to the complete code structure: Node.Js Code Structure

Final Thoughts:

This code structure is in its initial evolutionary process. Your contributions to this structure will be highly appreciated.

--

--