At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

An Ultimate Architecture Flow For Your Next Node.js Project

  • By Vijayendran Karthikeyan
  • February 20, 2020
  • 3977 Views

Node.js framework supports JavaScript language natively. In the case of application development, other transpiler languages such as TypeScript or CoffeeScript can be used. In this blog, let’s build a Node app structure using JavaScript with Express.
You might have known that the Express framework doesn’t have a strict file and folder structure. For a small application, you can write the code directly on routers. It becomes easy for a quick start. One of the major issues in building a perfect structure is when the application grows, it becomes difficult to manage the code. So, let us find ways to avoid it and define our own app structure.

The App structure – Node.js Project

When we have different files and folders for each step, it will be to easy to manage. So, I have prepared this application structure to make it really easy for your next Node.js project. This structure is based on the Model-View-Controller(MVC) design pattern. The pattern is perfect for large scale projects as well as small ones.

Folders

This is a sample structure with how each folder contributes to the app structure as the main focus.

.
├── bin
│   ├── example
│   └── www
├── config
│   └── example.json
├── controllers
│   └── auth
│       └── login.controler.js
├── helpers
├── libs
├── middlewares
├── models
├── public
├── routes
│   └── auth.js
├── services
│   └── auth.service.js
├── validations
│   └── auth
│       └── login.validate.js
├── views
├── app.js
├── .env
├── .gitignore
├── package.json
├── package-lock.json
└── README.md

Routes

Routes are used to map the specific URL with the associated function. In this structure, it connects the URL with the controller function.

Example

const login = require('./../controllers/auth/login.controler');
router.post('/auth/login', login);

Middlewares

Contain global middlewares. Common validations like Token, User access, Max input size, Content type, and Access header validations are handled inside the global middlewares.
In general, there are two types of middlewares are available.

  1. Request middlewareIt validates the incoming request and acts as filters from accessing the application.
  2. Response middlewareIt used to format and log the application response.

Example

app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

Validations

Validation files also one kind of middleware. But this folder contains route specific middleware. Instead of writing the validation inside of the controller, we can organize our request validations inside of the validation folder.

Example

// login.validate.js
var Joi = require('joi');
module.exports = {
 body: {
   email: Joi.string().email().required(),
   password: Joi.string().regex(/[a-zA-Z0-9]{3,30}/).required()
 },
 options: {
   status: 422 // use 422 for request validations
 }
};

Controllers

Controller files are responsible for connecting service and view templates after validation.

// login controller.js
var validate = require('express-validation');
var loginValidation = require('./../../validations/auth/login.validate');
var authService = require('./../../services/auth.service');
const login = (req, res, next) => {
 console.log(req.body); // => { email: "user@email", password: "pwd" }
 let response = authService.login(req.body);
 if(response instanceof Error) {
   return next(response)
 }
 res.json({
   "status": "success",
   response
 });
}
module.exports = [
 validate(loginValidation), // step 1 connect validation
 login // step 2 connect service and return response
]

Services

This folder contains all the business logic.

Models

Each collection/table has a corresponding “Model” file which is used to interact with that collection/table.

Views

Contain layout templates for the web page representation

Helpers

It contains common functions for the project.

Also Read: How To Collect, Customize, And Centralize Node.js Logs

Public

Contains all the static files like images, style, and JavaScript

Bin

Contains all the scripts for code build and deployment

Lib

Third-party systems should be loosely coupled (Handling). So always create a separate library file, when you connect a third-party system like a cache system, payment gateway. It will help when you switch to a different system.

Config

Environment-related configuration comes from .env file. But the config folder contains application related configuration like max limit for pagination.

Files

Naming conventions

Node module names are generally lower case and dash-separated. So keep it the same for the custom modules. Also, we can split the multiple files for the same endpoint. For example, login endpoints have login middleware, login controller, and login service file. Everything you need will be present in different folders with the same file name as login.js. To avoid confusion, you can just add a suffix like register.controller.js. It’s very helpful at the time of search by giving the filenames in code editors.

Example

.
├── controllers
│   └── auth
│       └── login.controler.js
├── routes
│   └── auth.js
├── services
│   └── auth.service.js
├── validations
   └── auth
       └── login.validate.js

File size

Keep the file size as small as possible. Writing too much code in the single file might confuse others especially if your working in a large team. As it affects the developer’s readability and also editor productivity. It also occupies too much memory space. For better readability, it recommended setting your limit as max 200 lines per file.

README

README file is a text file that contains information about the project and deployment steps.

Sample Readme

# Project Title
Project description goes here
## Getting Started
Instructions to set up your local machine for development and testing purposes.
### Prerequisites
Things you need to install the software and how to install them
```
examples
```
### Installing
A step by step examples that tell you how to get a development env running
```
example
```
## Deployment
Instructions to setup live environment
## Built With
* [Express](https://expressjs.com/) - The web framework used
## Versioning
We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags).
## Authors
* **YourName** - *CompanyName* - [SocialMedia](https://twitter.com)
## License
License information goes here

app.js

It contains the code to initialize the express application.
Take a look at the full sample repository here!
I hope this article helps you in your architecture planning for your next NodeJS project. Shoot your thoughts and questions on this architecture. we will help you out.
Need something interesting on Node JS? Never miss another newsletter. Get weekly updates on development technologies by subscribing to our newsletter.
Is NodeJs a perfect framework for your development? Talk to our tech experts today to develop your ideas into a world-class business. Need to start a project? Hire JavaScript developers from Agira Technologies and fulfill your digital desires and scale your business higher by getting our solution to your market.

Turn your vision to magnificent reality With
Our Web and Mobile Solutions

Vijayendran Karthikeyan

Vijayendran is a software developer with 7+ years of experience with various development technologies. Expertise in PHP and NodeJS. He always evolves with new ideas and new learnings. He is not only a passionate tech geek but also becomes a movie bug in his own space.