DEV Community

Cover image for How to Structure Your Backend Code in Node.js (Express.js)

How to Structure Your Backend Code in Node.js (Express.js)

Vishal Yadav on July 17, 2024

When developing a Node.js application using Express.js, structuring your codebase effectively is crucial for maintainability, scalability, and ease...
Collapse
 
florianrappl profile image
Florian Rappl

While the micro scheme is fine, it lacks a proper repository structuring.

As an example, not aggregating the source code in a src directory is a huge misstep. You might want to use TypeScript or some other tooling (e.g., a bundler) to process your code for performance benefits. As such putting everything into the root / mixing with your tooling and tests is something you want to avoid strongly.

(You should not use CommonJS - use ESModules; especially if you really care about "maintainability, scalability, and collaboration".)

Collapse
 
jjco790923 profile image
Juan José Cruz Ortiz

you are wrong since the moment you want to put types to a non typed language, if want types go and do you stuff in c# or java

Collapse
 
florianrappl profile image
Florian Rappl

My comment was independent if you like or want to use TypeScript. That was one example. Having a src directory is pretty much always helpful (as you might want to bundle for performance reasons).

Maybe instead of making useless comments it would be great to improve your knowledge about JS and its ecosystem from time to time. Might help.

Thread Thread
 
jjco790923 profile image
Juan José Cruz Ortiz

If you had a good understanding of js you wouldn't have to use typescript in the first place, and secondly you've obviously never worked on any big enough project where the ShitTypescript spends 2 hours making bundles for perforance reasons at every line change

Thread Thread
 
nguyendat251 profile image
NguyenDat251

Working on a big project without needing Typescript? You are the one who sounds like you have never worked on any big one. That is Typescript's purpose: to add typing syntax for js, to let the code document itself. So when the project is scaled up, people can join and easily follow up the codebase.

Thread Thread
 
vyan profile image
Vishal Yadav

Yeah , you are right , I'm solo freelancer! but it will help who is new in this field.

Collapse
 
adesoji1 profile image
Adesoji1

if i want to convert the javascript application in ES module to a desktop application using electronjs, how do i do it?

Collapse
 
florianrappl profile image
Florian Rappl

Electron.js understands ESM (electronjs.org/docs/latest/tutoria...) - but if you want to only use ESM in development and another format (e.g., CommonJS) at runtime I recommend using a tool such as esbuild (which can bundle and transform).

Thread Thread
 
dev_dive profile image
Chibueze Onyekpere

Thanks for the new insight.

Collapse
 
vyan profile image
Vishal Yadav

using tools like Electron Packager or Electron Builder.

Collapse
 
adesoji1 profile image
Adesoji1

nice work, thank you for this, for a react frontend that has typescript in it, how should the folder structure be arranged?

Collapse
 
florianrappl profile image
Florian Rappl

Just put everything in a source and write the code as-is. (e.g., then src/index.tsx instead of a index.js or src/index.js). Use a tool such as esbuild to consume the source files and transform (+ bundle) them into a dist folder (src/index.tsx and related files -> dist/app.js).

It's a standard practice that pretty much all applications today follow.

Collapse
 
vyan profile image
Vishal Yadav

I will share soon!

Collapse
 
asisshukla profile image
Ashish Shukla

That’s well said but if we are really aiming that big and complex applications, then we should use another frameworks like nestjs which provide all these things out of the box.

Collapse
 
clarenceliu86 profile image
Clarence Liu

I agree, this is fine for JS, but any serious project should really be using Typescript as you said, type-safe SDKs are super powerful, see Tanstack Router or others that are built with this in mind.

Collapse
 
r9n profile image
Ronaldo Modesto

Very good article 💯. Structuring projects is a more difficult task than it seems because we have to think about possible developments and how they can be accommodated in the least painful way possible.
If you allow me, I would just like to make a suggestion for improvement.
The regex used to validate email is vulnerable to ReDos (Regex Denial Of Service). It would be interesting to perhaps try to replace it with another one in the article so that other people who come to read the article don't end up using this regex to validate data in real systems.
Here's a tip for readers, always validate your regex before using.
I generally use this site to check if a regex is vulnerable: devina.io/redos-checker
Once again congratulations on the article 😃

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
rcls profile image
OssiDev • Edited

I have always had a bit of a problem with this type of folder structure. I don't understand how you can modularize your code with it. You have, at the root of source directory, the typical controllers, services, repositories (application, domain and data layers) folders and inside those you have similarly named files and classes, like "customer" or "product". While the controller, the service and the repository for "customer" belong together, they aren't close to each other, so it's harder to make that connection.

I always considered it better to have a modules/ folder inside which I have the customer and product and inside those folders have layers like controllers/, services/, views/ and persistence/ or repositories/ etc. This way I can easily focus on working inside one module, and if I need to, I can easily separate it to it's own service.

A tip there is to use DDD, so that you create modules based on the bounded contexts and you can easily create microservices based on those bounded contexts. Yeah, you will have more nested folders, but you still have a more clear grouping and separating them later (if needed) is much less painful.

Collapse
 
jjco790923 profile image
Juan José Cruz Ortiz

horrible i hate it its dumb

Collapse
 
omara_patrick_809b3562f29 profile image
Omara Patrick

The code looks well organized and readable

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
yourakshaw profile image
Ayush Kumar Shaw

Thanks for this amazing writeup, Vishal. ❤️ed it!

It'll be great if you can share a sample GitHub repo for referencing a similar project structure. Would be a great addition as a reference material.

That said, I recently came up with a backend microservice template using JavaScript, Node.js, and Express.js. Although incomplete, it's quite practical and can be used to build reliable backend services. In my template though I've taken inspiration from NestJS for their modular approach to the directory structure.

Your blog though is a great reference for me to build another template, one that corresponds to the more common way of organizing the project, the way you've portrayed here.

So again, thanks! 💯

Collapse
 
vyan profile image
Vishal Yadav

Thanks, bro means lot

Collapse
 
beauspot profile image
Iyere Handsome(Beau) Omogbeme

Not going to lie this directory structure is archaic and for beginners who are new to expressjs. There is are far more approachable and preferable ways to structure an expressjs app, most especially when working with typescript at the backend.

Collapse
 
jokello profile image
James Oduor • Edited

Good job this is well done. I think for me as a beginner it's the principle. whichever approach one choses it must satisfy the principle of separation of concerns. For those criticizing I think it would be best to support your claim with a well organized and concise alternative as this presented herein rather than hate and throw things here and there. Once again good job @vyan 🇰🇪

Collapse
 
srishtikprasad profile image
Srishti Prasad

Nice insights!! @vyan

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
array_dot_reduce profile image
Bhaskar Ghale

It might have been better to dive into one of the popular start kits and explore why they are structured that way.
But this is a good one nonetheless!

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
juka0920 profile image
Joana Pereira

Can you share the links for those popular start kits?

Collapse
 
vyan profile image
Vishal Yadav

Yeah

Collapse
 
yogesh_joshi_c022cc46cdd6 profile image
Yogesh Joshi

I request to you if possible then create GitHub repo for us. that more help to beginner like me.

Collapse
 
vyan profile image
Vishal Yadav

Yes , I will create!

Collapse
 
yogesh_joshi_c022cc46cdd6 profile image
Yogesh Joshi

thank you...

Collapse
 
sina_heydarinejad_af63a41 profile image
Sina HeydariNejad

thanks for all the information :) huge hug from Iran .

Collapse
 
biparker profile image
Biparker

Thanks for the guide, as a beginner ejs coder, I deployed my first website to be used by my coding learner group. Will help rewrite and organize.

Collapse
 
vyan profile image
Vishal Yadav

Welcome!

Collapse
 
dubemkizito profile image
Izuorah Dubem kizito

I prefer modular setup. Makes it easier to scale up or down by attaching or detaching modules

Collapse
 
vyan profile image
Vishal Yadav

Cool!

Collapse
 
raselldev profile image
raselldev

better using per services area

Collapse
 
tigawanna profile image
Dennis kinuthia • Edited

i've been preferring grouping related items to the point where i can copy the posts route directory into another project and it would mostly work

Collapse
 
notgamedev profile image
Amin Jalal

hi

Collapse
 
thegreytangent profile image
Jason V. Castellano

So far so good (-:. You can add repository later for your queries and create entities for your business logic.

Collapse
 
mahmoudwalidjs profile image
Mahmoud_Walid

Oh, Thanks, This is what I was waiting for ⭐

Collapse
 
vyan profile image
Vishal Yadav

Cool

Collapse
 
benikad profile image
BENIKAD

Nice work here

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
prashasthnair profile image
Prashasth Nair

Nice Explaination.

Collapse
 
vyan profile image
Vishal Yadav

Thanks!

Collapse
 
programordie profile image
programORdie

Very usefull! Thank you for writing this

Collapse
 
vyan profile image
Vishal Yadav

Nice!

Collapse
 
martinbaun profile image
Martin Baun

Thank you very much for another insightful and important article!

Collapse
 
vyan profile image
Vishal Yadav

Welcome!

Collapse
 
divyangchhantbar profile image
Divyang Chhantbar

Thanks for posting Vishal , infact i am also following somewhat like this structure only and believe me it helps a lot and make it less complex for the devs to understand stuff.

Collapse
 
vyan profile image
Vishal Yadav

Welcome buddy!

Collapse
 
bartdev profile image
Wojtek

DDD hex

Collapse
 
dev_dive profile image
Chibueze Onyekpere

I really like this post. Let's connect

Collapse
 
vyan profile image
Vishal Yadav

Yes , you can see my social handle on my profile!

Collapse
 
mitesh_bhagwant profile image
mitesh bhagwant

Please share GitHub repo.

Collapse
 
vyan profile image
Vishal Yadav

I did not created GitHub for this!

Collapse
 
liansun96 profile image
liansun96

Yoooooo

Collapse
 
dev_dive profile image
Chibueze Onyekpere

Thank you for this. I believe well structured code will save me from a lot of headache

Collapse
 
vyan profile image
Vishal Yadav

Welcome!

Collapse
 
aditypraa profile image
Aditya Pratama

why don't you put it in the src folder

Collapse
 
vyan profile image
Vishal Yadav

Because , I see most people use this way only, You can put your code in src , it will be more structured.

Collapse
 
aditypraa profile image
Aditya Pratama • Edited

if I use express generator do I have to put it in the src folder?