Starting an express application from scratch? You have come to the right place. In this post, I will share how I have been structuring my express applications. I have been using this for a while now.
Folder Structure
For any project folder structure is a crucial part. It helps to create a practice that will help you in your development life cycle, collaboration with your team and last but not the least – in transferring the code to someone else for maintenance. With the open source community catching up fast, all of these become very important.
So, lets look at the folder structure which I normally use for a standard express app based on Nodejs.
Few lines about each of them.
Folder | Description |
---|---|
config | This folder is for all common configurations. |
controllers | This is where I manage all my routes using any framework. |
helpers | The place for all helpers utilities – encryption, date, string, formatting, transformation, logging etc. |
middleware | The place for storing all middleware functions. This is specifically for authentication & keylogging majorly for me. |
model | This is where I put all my model classes for interacting with the database. It can be any database framework. I personally prefer MongoDB |
ui | This is the location of your UI code that needs to be served by the NodeJS server. It can be Angular, React etc. My personal choice and recommendation – Angular. |
<BASE> | This is the root directory of your project. Key files to mention are – index.js (server), db.js (database initialization) and .gitignore. |
Default Packages
You have to be very sure about the packages to use. The basic guideline I follow is “Keep it to the minimum and use only if you want to utilise the full functionality of the package”.
Below are mandatory packages which I use with my NodeJS – Express application.
- axios, my goto promise based HTTP rest-client library.
- body-parser, parsing JSON data for modern APIs
- compression, to reduce payload size and optimize for production.
- express, the API framework
- helmet, to remove all the unnecessary security headers which give more information about your application. Trust me – use this.
- jsonwebtoken, my goto library for JWT
- pm2, a process manager to run the application to support the load
- cross-env, if you want to run commands on all platform – windows, Linux.
- nodemon – hot reload for your express application.
Getting Production Ready
Always use a process manager. I prefer PM2 as mentioned in above dependencies. I am just getting too much used to PM2 (https://pm2.keymetrics.io). They have just grown to a more professional level to support the process manager function for node applications. From process manager, dashboard, logs, metrics – too much information this small utility provides. Give it a shot – you won’t regret it.
Hope you liked the post and found it useful in some ways. What tools or packages you use? What’s you goto folder structure. Please share your thoughts.