As I began developing REST APIs on the server side with Node.js, I repeatedly faced the challenge of determining the appropriate folder structure. Although there is no definitive answer to this issue, I discovered a Node.js folder structure and architecture that suited my requirements after reading several articles on the topic. In this post, I would like to share my approach to organizing and structuring Node.js REST APIs. Additionally, I have created a GitHub repository that includes a sample application which you can utilize as a template for your own project.
It is worth noting that my implementation employs Express.js as the web framework and TypeORM as the ORM. However, adapting this folder structure to other frameworks should not be too difficult.
The architecture mainly relies on a component-based approach, making it easier to request only the necessary data. For instance, we have a User component that encompasses all user-related information.
Letβs start with the root directory.
Directory: root

The root directory is fairly ordinary and ought to be familiar to you. It essentially constitutes a fundamental Node.js configuration that encompasses certain configuration files for linting, Docker, and other similar components.
However, the most intriguing aspect of this structure lies within the contents of the "src" folder, which this post specifically discusses. Consequently, what precisely does this directory contain?
Directory: src/api
Directory: src/api/components

At the core of our Node API based on components, we find the following: every component has its own set of routes, controllers, models, repositories, policies, tests, and templates.
Now, let us delve into the User component and explore it in further detail.
Directory: src/api/components/user
Directory: src/services
This directory contains global services we might need for authorization, sending mails, caching, or helper methods for example.
Chekcout my github repo to see all the files and how code is organised
https://github.com/Rcoder0907/node-folder-structure




Top comments (0)