It's time to ditch Medium for good! ūüĆą‚ö°ÔłŹ

Introducing Devblog by Hashnode. Blog on your domain for FREE. Highly customizable and optimized for developers.

Learn more

How do you structure folders in your NodeJS backend?

I want to know about your NodeJS backend structure.

Thanks a lot!

Write your answer…

3 answers

It depends on the scope of the project. I like to start simple and restructure, or extract functions and route handlers, as the application starts to grow.

For me, typically it looks something like this after I've gone through the restructure process:

# Ol' (oftentimes) reliable

# Configuration is a topic for another time, and entirely situational
# Just imagine some config.js/json/.env/.yaml/rc file somewhere here
# Typically I just use a file that will load from env variables and set defaults, and I'll just require it as necessary elsewhere

# Kick-off file. Imports the app/server instance from app.js and initializes and runs it.
# In the case of an express app, would bind to a port and start listening.

# Exposes an app/server instance. Can be an express app or something similar.
# In an express app, this would be binding the routes and such

# Any functions and such, organized by functionality or feature

# This is really only relevant for http servers. 
# Controllers to me are just objects with route handlers.
# I just group them by feature, or sometimes even path

# This can really be a directory or a file
# But all it does binds the functions from controllers to the appropriate routes

# Models are entirely situational too, and only relevant when using a database
# Can also be a file or directory (K. I. S. S.)

This is entirely my opinion of how to do this. Another pattern I've been doing most recently has been grouping controller, route, and model together in a directory by feature/component/service in place of the separate route/controller/model directories/files to simplify things. I can sometimes even put all three in the same file if they're small enough and avoid the directory altogether. Then I just have the top level files that bind and register the handlers and kick things off as usual.

Oh, Thank you, sir. Now I usually use the structure like your structure.

Reply to this…

Share your programming knowledge and learn from the best developers on Hashnode

Get started

Hey jarupong pajakgo, please clarify your question a bit and use the appropriate tags. This way, your question is invisible to others.

Please ping me as soon as you're done with the edits and I'll list your question back.

Reply to this…

Hey there! I have gone ahead and un-delisted your post. In future please tag your posts so that they get visibility. :)

Oh This is my first time to use Hashnode Thank for your advice, sir.

Reply to this…