Node-Express basic Project Setup with folder Structure for beginners
Tags: javascript, beginners, programming, node
Published: 2021-12-08 15:22:11

![Clean Code Architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5puy40vslh780kanh5ra.png)
 
Over the last several years we’ve seen a whole range of ideas regarding the architecture of systems. These include:

[Hexagonal Architecture](http://alistair.cockburn.us/Hexagonal+architecture) (a.k.a. Ports and Adapters) by Alistair Cockburn and adopted by Steve Freeman, and Nat Pryce in their wonderful book [Growing Object Oriented Software](http://www.amazon.com/Growing-Object-Oriented-Software-Guided-Tests/dp/0321503627)
[Onion Architecture](http://jeffreypalermo.com/blog/the-onion-architecture-part-1/) by Jeffrey Palermo
[Screaming Architecture](http://blog.cleancoders.com/2011-09-30-Screaming-Architecture) from a blog of mine last year
[DCI](http://www.amazon.com/Lean-Architecture-Agile-Software-Development/dp/0470684208/) from James Coplien, and Trygve Reenskaug.
[BCE](http://www.amazon.com/Object-Oriented-Software-Engineering-Approach/dp/0201544350) by Ivar Jacobson from his book Object Oriented Software Engineering: A Use-Case Driven Approach

Don't get panic to see above architectural article, all above only for your reference, if you wish to read and gather knowledge you can through the link. 
See below article to create a express server and project setup step by step.

## Basic setup step by step
Open cmd and go to your desired folder now write -
`mkdir cleancodeStructure`
`cd cleancodeStructure`
`npm init -y` to initiate the **package.json** file into your project you will see in sidebar- ![package.json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gtdrbu8w77qvgamxujm8.png)
now install few package into your project to make it trackable and maintainable and workable-
`npm i express cros morgan dotenv`
![dependencies](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxbjbtqifx0guu50ogvw.png)

also install nodemon to keep your server ups and running once start 

`npm i -D nodemon` -D as a **devDependencies**
![devDependencies](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dwlpvmmamd7je9yyiyol.png)
 
 now create **server.js** ![server.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/stc62v3z0ttmz1wghu1f.png)
 
in the same level of **package.json** ![package.json](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ymsm8np9235oxw6u968.png)
 
import some necessary file to server.js like below
![import some necessary file to server.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b4hdeym1m978vek6nlhu.png)

and write few lines of code to make a **nodejs server** like below Please give online line break-
![server.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a1ihyubt10hkeinkq176.png)
now come to the next level of app and router section which you already included in **server.js** but not yet created.

create **app** folder in the **package.json** level and create **app.js ** to create express app for your project
 ![App Folder with app.js to work with app level codebase](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c5w01i4mm5utlv0rzuh8.png)

**App Folder** with **app.js** to work with app level codebase
 
now **import express** into the **app.js** file with **getAppHealthCheckerController**, don't worry will talk about **getAppHealthCheckerController** later.

![import express into the app.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ldp3qxfzfwiyn5ie3j3.png)

now come to below line and create a express app like below
![express app](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92gx6fkeiuwl6dolt3hg.png)

then define a **route** for **app health** called **/health** route in the **app.js** like below and export express app - 
![the app health route](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q1fows0nj5bhzig6ihqi.png)

now come to the router controller part, I mention above that, I will discuss about **getAppHealthCheckerController** latter, now time to discuss in a short about app health route and Controller. 

**/health** route
Most of the server for backend API they checked one route that must be exists. do you know what is that? ok, I am telling you this is called **/health** route. [digital ocean](https://www.digitalocean.com/) one of the server service provider look first for **/health** route. if API has health route they think that the API server health is good. generally this route expect status code 200 in response back.

now create **controller folder** in the **package.json** level or **first level** and **app.js** controller inside the controller folder like below ![controller folder](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/isqhz28h2qpbpizc3c3m.png)
 
and code inside **app.js** like below-

![app.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9sfkfmja9hiumo0p9ym.png)

now config your **package.json** file script like below -
![script dev](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bzfyibwjfkasgbbj8a4r.png)

now you are ready to check your **/health** route from browser.
go to terminal of of your **vscode** and type `npm run dev` and hit [http://localhost:4444/health](http://localhost:4444/health)

**its time to Bloom**

![http://localhost:4444/health](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awda6129wbeg9yc1z4vq.png)
 
Welcome you made an express app with the health route; you are almost done to go a good way to write your code in a good structure.



now create a **routes** folder with **router.js** file like below example.
![routes folder with router.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29t07uc1zz0ss3rykojw.png)

and create some route like below
![some route](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/23ozck2i0unjc5n5lfn5.png)

then go to **Controller folder** to create some controller which you attached with the above **new route** (**getHomeController**, **getBlogController**, **getBlogByIdController**), in **router.js** file.

at first create **home.js** in **controller folder** and write some demo code for home route like below.

![home.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9fy3krsfsu0yblsgax29.png)
Secondly create **blog.js** in **controller folder** and write some code for blog route like below.

define a blogData variable to write demo blog data for example -
![blogData](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7ydvtkqj5e5cd191c1n.png)

now define a controller function `getBlogController` like below to make the **/blog** route workable and to see the blog API and paginate the Blog API;

![getBlogController](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/imlgsyyp5ejvhit8pnu5.png)
 
I keep the all the code in this controller to make it simple, you can separate with the middleware.

now hit http://localhost:4444/blog

![Blog](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ph4doqwmz8r6frbrd87r.png)

you can paginate the Blog API like below [http://localhost:4444/blog?page=2&limit=1](http://localhost:4444/blog?page=2&limit=1)
![Blog API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s1p8bw1i05u0f0vgkho.png)

now create another route controller to get the blog by id. Its very simple to get specific blog data no matter where it is coming it may come from **mongodb** or **javascript object** or **JSON data** or some where else, see below how to get data from javascript object by controller function in **blog.js**

![blog.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g7dz96iv4cq1w83c3b34.png)

and export both controller function, 

you can create **index.js** file to export your all controller function from the controller folder together which will
help you a lot to minify your code base and keep your code clean. 
 
![index.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xr5s3hmj61nv3ek3dp5v.png)

![index.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2wmzmxn8wasz0pnuz180.png)
 
when you call the specific controller you just need to call the `const { yourController } = require('../controller');` and extract the specific controller to use.


![Wow](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9d7lfsxrpr1en0da2psh.gif)

we are almost done, now see some middleware and wrap up for now...

## middleware 

**Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.**

**Middleware functions can perform the following tasks:**
- Execute any code.
- Make changes to the request and the response objects.
- End the request-response cycle.
- Call the next middleware function in the stack.

 
> **If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.** 
 
how to create a middleware and how to use see below example and folder structure  

now create a folder called **middleware** like below and create a demo middleware for testing purpose.
![middleware ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rm4jwbb902ev80507wgy.png)
write some code like below to demo.js middleware
![demo.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ci8l1cxqwge7ov5l5sdk.png)
 
import and use to **server.js** for all route 

![Server.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fuuxekpn46eybo2nt3r.png)

See middleware is working--
![middleware](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z95v6k4ky5rrcgj71su0.png)
for more details [click here](https://expressjs.com/en/guide/using-middleware.html) to visit express.js

## Error handler 
you can create error folder in first level and create your own custom error handler, like below

![error handler](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b8ybzla0zcn9uss47nrc.png)
**errorHandler.js** code sample looks like -  

![error handler](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wcu3q2o9cm98rjf0op1s.png)

use it in **server.js** like below by using **app.use()** 

![server.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nohhdyv42ui9tw9e4myz.png)
if error occur error message will show of the unexpected route 
![error message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hl3y9xryjq91ptgek6p.png)

**you are almost done with setup**

Now you create all other folder for your convenient, it may be anything which one is required for your project, like below- 
log, service, public, utils, db, models etc as per your needs

![Folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lj9mnex88ujanjc8xbdu.png)

![thank you](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t12y8gkhar83u3pbd5vb.png)
 
[You can see a video more about NODE and Expressjs server and Paginated API creation-](https://www.youtube.com/watch?v=Je_Zpf2snmQ&list=PL15CsFQf-JdzcYTsiOHM1pbgowXe-g2Fm)

You can learn docker from this [video](https://www.youtube.com/watch?v=RC9yxMcXquI&list=PL15CsFQf-JdzNcfMCSRmywaEkNNsbt5Xv)

> **that's all about folder Structure and node express server creation with error handling and middleware**

`
Above all I am human being, I have lots of mistake and lack of knowledge. So if i made any mistake and provide any misinformation, please correct me and pardon me. 
`

![kudhahafez](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iwrfq54sdjmiuh4k9uln.gif)