In ExpressJS, we always have to start from scratch for things like CSRF/JWT Token, Exception Handling, Clusters, Queues, Cache, etc. So, I thought to make a boilerplate to kick start with technologies like Typescript, MongoDB and Pug Template.
You can find the repository on GitHub — geekyants/express-typescript.
#1. Exception Handling
Rather than restarting the entire node app again & again for minor bugs. We found our way out to handle exceptions & errors using Node’s process events. So now we catch these errors & exceptions using Handlers and show our users a custom page.
#2. Fork a New Cluster on Exit of Old Cluster
Rather than sending the entire load onto a single Core / CPU, we try to take advantage of a multi-core system to handle the load. Here, if the cluster dies due to some reason, we create / fork a new one immediately.
#3. Authentication (E-Mail with OAuth)
Using PassportJS as an interface, we keep adding configurations & registering them in the app for social authentication.
A Single Log class with methods like info, warn, error & custom.
These methods send the log string to a file under .log directory of your project root and keep creating these log files daily rather than having a single log file.
You can zip them every week too!
Use of .env file, to load environment variables/constants for the entire app. So now, we have a single centralized constants location.
We prefer using CSRF token (stateful) for our Web routes whereas JWT token (stateless) for the API routes. So, here we create middlewares for both the tokens and registered them against Web and API routes respectively.
Structuring of folders/files structure in ExpressJS was a bit of a discussion.
Where to organize which files? Or is there even a perfect structure? At last, I came up with the following folder structure.
Note: The screenshot contains just parent level folders only.
There are various things in backend logic that do not really need to happen onto the request.
Things like sending out E-Mails or SMS texts, etc. So basically, things that require a connection to any third party service.
For this, I have used KueJS, a priority-based job queue that runs on a Redis driver.
For the caching of web routes, I‘ve used a simple in-memory cache using memory-cache.
And many more…
About Me 👨💻
I'm Faiz A. Farooqui. Software Engineer from Bengaluru, India. Find out more about me @ faizahmed.in