This content originally appeared on DEV Community and was authored by Samar Mohan
Introduction
There are so many ways to structure a Node.js and Express API and each one has its own pros and cons. In this post I'll detail the two main ways, MVC and modules.
Note: I'm not going to keep adding "Easy to understand" and related pros becausethis is all based on opinion, pick one and stick to it!
The structures
Modules
Inspired by Django's apps
One way to structure an app is with modules. Each module contains all the code for a certain part of the app like auth
or posts
. Each folder will have the controllers, routes, entities, and middleware.
An example of the auth
module is above. You structure the auth
module your own way, this is just mine. You could use an MVC pattern inside the module and some people may want to strip out the middleware and entities.
Pros:
- Easy to work on a certain feature, everything is in one place.
Cons:
- You may not want everything bundled up like that.
- You'll have to use
fileName.typeOfFile.extension
instead of justfileName.extension
.
MVC
Used in Phoenix, Rails, and ASP.NET Core
This is by far the most common way to structure a backend project and many popular frameworks use it. You have your controllers (logic, handling requests), views (ui), and models (database schemas, business logic).
An example of MVC in action. The auth
controller will have the register, login, and logout methods. The model will have the database entity fields, and the view will be what the end user sees.
Pros:
- You know how everything interacts
Cons:
- Multiple folders
- Repetitive
- You need to understand the why behind MVC
Thanks for reading! I hope this cleared up some things for you.
This content originally appeared on DEV Community and was authored by Samar Mohan
Samar Mohan | Sciencx (2021-08-12T16:55:01+00:00) Structuring a Node.js and Express Backend. Retrieved from https://www.scien.cx/2021/08/12/structuring-a-node-js-and-express-backend/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.