Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing Node apps.
We should use Helmet if we’re writing a web app.
It does a few things, including:
- add XSS protection
- prevent clickjacking with
- enforcing all connection to be HTTPS
X-Powered-Byresponse header so attackers can’t narrow down the libraries we’re using to write the app.
Helmet will set sensible defaults for all those options.
We can install it by running:
npm install helmet
In our Express app, we can use the middleware by writing:
const helmet = require('helmet'); app.use(helmet());
If we’re running our app, then we need to monitor it.
Users aren’t happy if our app goes down and there’s no quick resolution.
Therefore, we need to monitor our app and alert everyone so that we can get it running again quickly.
For instance, KeyMetrics.io integrates with PM2 to check for the app’s health.
A dashboard is also provided to show us when it’s up or not.
Latency and events can be checked.
We can test our code with automated tests so that we have peace of mind when we change our code.
They run quickly and automatically so that we don’t have to check every part of our app ourselves.
We should add tests when we fix bugs and run our tests regularly.
There’re a few ways to run tests.
We can use Mocha, Chai, Jest, or Jasmine to run them.
They’re all popular and provide equivalent functionality.
To create tests that make requests, we can use Supertest to make the requests and check the results.
We should structure our project by components.
This way, we can find them later.
It’s easy to get lost if a project has no structure.
We should divide our code into modules.
We should only use Express for the controller portion of the app.
Business logic should be in their own modules to organize our app better.
This way, each module, and function does its own thing.
Mixing different parts together makes them hard to test and maintain.
If we have common things that are used in multiple projects, we should put them in their own package.
Common functionality like logging, encryption, etc. should be in their own package.
This way, we only have to change one package to update the functionality.
Our Express app shouldn’t be one big file.
The entry point should be separate from the rest of the app.
One big file makes everything slower.
The API should be in
app.js and the networking code should be in
The API declaration can also be split into component if it’s big.
We can organize our app better.
Also, we can take steps to improve security and monitor our app.