Node.js Project Structure

Learn via video courses

Overview

Developing applications requires developers to follow structural patterns so that the codebase is easy to read, share and maintain.The best and the most popular approach is to segregate code into modules which can be exported and imported within the other modules. This ensures that the same piece of code is not repeated and it is easy to scale the application. This also ensures that the code is easy to debug and easily understood even by new developers.

Pre-requisites

Here are the pre-requisites required for this article:

  1. Basic knowledge of NodeJS and NPM.
  2. Basic knowledge of MVC architecture (Model, View, and Controllers).
  3. Basic knowledge of REST APIs.

Introduction

NodeJS backend photo

NodeJS is the most popular JavaScript runtime environment in the market today. It brings JavaScript right to your back end. This means that applications can be developed end-to-end in JavaScript. While developing these applications, it is paramount that a good foundation is provided to the code base.

What do we mean by the foundation? It means that we give our application's code, a well-defined structure. In this case, for our NodeJS application, this would mean giving it a proper Node JS project structure. This becomes even more prevalent in large applications with thousands of lines of code.

Why Node JS Project Structure is Important?

It is not only important for the code to be working but also for the code to be readable. A good codebase is one that can be easily read and navigated. If a new developer were to look at the application's codebase, then they should be able to understand the code and work on it too. Let's highlight a few points as to why a good Node JS project structure is important:

  1. It organizes the code into separate files, folders, and subfolders. This brings modularity to the code.
  2. Developers know the importance of not repeating themselves and a well-structured NodeJS project prevents re-writing the same piece of code.
  3. It helps to segregate the code logic into smaller chunks which makes the code much more reusable and makes the life of the developer easy.
  4. It makes it easy to scale the application. This means that if there is a good project structure, then it becomes easy to add new features without breaking the current application in production.
  5. Since the node js project structure is well-defined, error handling becomes much more accessible.
  6. This also leads to increasing the speed of development.
  7. Since the code becomes much more readable, the collaborative nature of the code increases immediately.
  8. The code becomes highly shareable and multiple developers can easily work together on the application.

Thus, we understand how important it is to maintain a strong application project structure. Now let's discuss some things to keep in mind while implementing our Node JS project structure.

Best Practices for Node JS Project Structure

Bundle similar logic in the same folder

This means that keep files with similar logic together in the same folder. For eg, if we have multiple controllers in our node js project, then we should group all the controller files in the same folder. Since all the controller logic is within the same folder,it is easier to locate and debug. In the future, if more files with similar logic needs to be added, then the developer would know to use this particular folder. The same goes for models, routes, etc.

The controllers should be thin

Whenever someone sends a request to your application, the controller would be the first line of defense. This means that the controllers should not contain any major business logic. Instead, there should be a separate folder for services with service files containing the important and sensitive business logic.

the Application Layers

Separate the database logic and business logic

The business logic should also be separated from the data access logic. Let's say we are using an ORM for our data, then we should define separate model files in a models folder and import them into our service files(business logic). This is important for our node js project structure because, in case of an error, the developer would know if the database or the business logic is broken.

Quick REST API reference

Use a Routes file to make API calls

Instead of using the main app file, we should implement a Routes folder with multiple route files in our node js project structure. A controller may have multiple routes and since we are segregating the controllers depending on the model and service, it only makes sense to separate the routes as well.

Node Modules should be in the root folder

The node modules folder is filled with the dependencies required in the project. It has all the packages. We need to access these modules throughout our project and they should be in the root directory and not in a sub-folder for easy access. Also, they should not be included in the git repository of the node js project structure as this folder takes alot of memory and not ideal of sharing. The package.json file stores the metadata which is shared instead of this folder.

Environment Variables in .env file

A .env file should be maintained in a good node js project structure. It contains all environment variables which are sensitive and should not be shared. These can include port numbers, API keys, database passwords, etc.

gitignore file should be used to prevent unnecessary files to be shared

Using a .gitignore file becomes mandatory to keep the size of the project small and increase security. Large folders like node_modules and sensitive data files like .env should not be uploaded to Version Control Systems.

Test Files should be included next to the logic files

Test-driven development ensures that our applications will not break under any expected or unexpected conditions. The test files should be coupled with the logic files and they should stay together.

Have a middleware directory

If there is any need to run authentications or validations, then our node js project structure must contain a separate directory for middleware. This would keep the pre-service logic away from the controller and improve security.

Now that we have discussed some of the best practices for our Node JS file structure, let's see how it looks in action! Here's a simple node.js application with a well-defined folder structure.

Revolutionize Your Node JS Exploration! Immerse Yourself in Our Full Stack Developer Course, Crafted by Industry Visionaries. Enroll Now!

A Simple Node JS Application

Simple Node JS Application

Let's look at the Node JS project structure for an Ecommerce Application. Here we have the complete back-end of the application. As we can see, these are the folders and files in the root directory:

  • Config - Contains the database and server configuration files. Simple Node JS Application 2

  • Controllers - Contains the javascript controller files. Simple Node JS Application 3

  • Middleware - Contains the middleware files for authentication and validation. Simple Node JS Application 4

  • Migrations - Contains the migration class files of our database ( here, tables of a database since SQL is used). Simple Node JS Application 5

  • Models - Contains the model class files created by our ORM. ( here SQL ) Simple Node JS Application 6

  • Node_Modules - Packages and dependencies installed using NPM. Simple Node JS Application 7

  • Routers - Contains router files used to route requests to controllers. Here we make the API calls to the database through the controllers. Simple Node JS Application 8

  • Seeders - Files used for initializing the database tables with data.(Not Required for the project. This folder is created by the ORM).

  • Services - Files with actual business logic used to access the database. Simple Node JS Application 9

  • .env file used to store environment variables.

  • .gitignore file used to mention the modules which will be ignored by GIT.

  • package-lock.json & package.json are used to store all metadata in JSON format.

  • server.js - This file is the starting point of our application with calls to all the modules and functions. Running this file starts the server.

Don't miss this chance to become a Node.js expert. Enroll now in our Free Node JS certification course & gain the skills to build fast and scalable web applications.

Conclusion

Thus, we can conclude the following:

  • Node JS is used for creating applications and the code base must have a well-defined project structure.
  • A good node js project structure has code segregated into files, folders, and sub-folders.This makes the code more readable and easier to maintain.
  • A well structured code is easy to navigate by all developers. This makes collaborative work easier.
  • Similar pieces of code or codes with similar logic should be grouped under the same folder. For eg., All services should come under one services folder.
  • Business Logic should be separated from controllers.
  • Database Logic should be separated from services.
  • Node Modules, config files, JSON files, and environment files also must have a proper structure in the node js application.