Structure Node.js App -  Fractal Pattern - 2019

This article about structuring the backend for REST API’s which can be extend to graphql.

Note: The article give an overview of structuring and here is the code base for detailed understanding.


After working with many backend projects, i realised that structuring the app is equally important as the choice of tech stack and fractal app structure is always my choice.

Fractal pattern convey that similar patterns recur progressively and the same thought process is applied to the structuring of codebase i.e All units repeat themselves.

Note: To code a fractal pattern and see it visually, check here and don’t forget to follow me on Github.

Now, lets start with the crux,

App Root Structure

The root folder always remain same in any case of API’s structuring.

So, At root level we have -:

1. app is where our main app code goes and will discus in depth under app structure below.

2. docs(optional) is for documentation purpose.

3. lib(optional) is where the complied app code goes which is used for production env.

4. migrations is where all the table schema. I personally use knex.js and an self made ORM name tabel written on top of it.

5. node_modules you already know it 😃.

6. tests is where we write all our unit test.

The structuring of tests folder is like the actions or routes under app folder and will be explained in app structure section.

7. config and config.sample.js are where all of our configuration related to database, authentication, external api keys etc are stored.

If you are wondering why we have two such files, then config.sample.js goes to your repository so that other developer can know the file shape and can use to form their local config.js file.

Also, we can also have a config.production for production environment.

Note: config can be a separate folder too, that can have separate sub configs files for database, external Api’s key etc but it feel overkill to me.

8. eslintrc is where the lint logic goes. Read more here.

9. migrate is the file that pass our configuration from config.js to ORM and help us run migration from CLI, check the code here.

10. gitignore is where we path to folder or filename that we don’t want to push on repository.

11. package.json — you already know it 😃.

Note: We will discuss only the app folder structure because other are straight forward. If you need any help or want to understand anything in code base then hit me up.

The app Structure

1. server.js is the file that start your server and will have all middleware that is required for request parsing like bodyparser, cors, multer and errorhandlers etc and finally we add routes middleware.

2. routes will have sub-files or sub-folders made as per the entities in project.

The index.js under routes looks like as shown below. It have request handler middlewares and a catch all route.

Note: We can abstract a big entity like teams in a folder and can call it as teams which can then have sub subfolder like members, contacts, dashboard etc. under routes.

A file under routes is where all request handler or sub-routes are written and the only purpose of them is to either call the action that is responsible for that route or the sub-route folder.

Note: signup, login, logout, refresh and forget password in above image all are actions that are defined under action folder.

3. Most of the times actions folder will have same the same structuring as the routes folder.

Each file in actions is for business logic i.e all code that store, get, change real entities either in database tables or doing queuing function like enqueue and dequeue etc all happen here.

Note: Actions can call other actions too.

4. So, middlewares, utils, helpers, tasks will follow the same way ofstructuring as action or routes do i.e main entity will act as a root folder and then will can have subfolder as per sub-entities and repeat.

5. tasks.js is used for running tasks from CLI created under task folder like database seed, clean database etc.

6. nsqd(optional) is use case specific for distributed messaging.

Note: NSQ is one the best i have used for distributed messaging it works great with no pain in production.

utils and helpers can be merged if need, i love to keep them separate so that i can reuse utils as its more generic in all projects

Why fractal

  1. Gives us phenomenal scale.

  2. Easy to debug as everything go with the domain logic flow.

  3. Easy to onboard a new developer to this codebase.


In Case of Graphql we can get rid of routes folder. Few month back i tried using this structure with Graphql check here (a raw sample)

If you are totally new to node.js and want to make a backend for REST API’s then use this. It contains everything you need from setup to authentication already done for you, just run the shell script.

Note: I personally use our own self created ORM called tabel which we have used in production for many years and i promise you will love it. This ORM and this app structure is all you need for making any kind of backend with REST API/GraphQL.


It is (and will always be) a work in progress on fractal pattern, i was recently working on removing the entire routes folder and exposing action directly to UI so that the UI can directly call the function with the required parameter which is what Graphql do but with REST API’s.

Fractal allows you to:

  • Reason about location of files

  • Manage and create complex domain entities with ease

  • Iterate quickly and scale repeatably


If anything is not clear or you want to point out something, please comment down below.

You may also like my other articles

Js ES6 Iterables and Iterators - 2019

Javascript - Generator-Yield/Next & Async-Await - 2019

This keyword In Javascript 2019 - Javascript Context

Javascript- Currying VS Partial Application 2019

Javascript Performance Test 2019 [Part-1] - for vs for each vs (map, reduce, filter, find)


Email

About Deepak Gupta

Deepak is profound programmer and financial educator in India. He has co-founded couple of startup from scratch and worked in more than 12 startup and big corporate with different roles.

Owing to his interest, he has been writing blogs regarding JavaScript and other framework to help people starting with it. Also, love to educate people about trading and cryptoworld in his free time.

Subscribe to our email list

More Tags Of Your Interest