Node js Best practices
Node.js best practices help improve the quality and performance of our application, and make it more secure.
Start Every New Project with NPM’s Init:
Npm init will automatically generate a package.json file for our project that shows all the packages/node app of npm install has the information of our project.
Unset
mkdir node-app
cd test-app
npm init --yes
Be Environmentally Aware:
As security best practices, we should keep our app-level keys easily readable from file and environment variables. We should also keep secrets outside the committed code and make a config file hierarchy for easier accessibility.This makes our app more secure and easier to manage.
Example:
Install dotenv to load the .env variables:
npm install dotenv
Create an .env file (in our project root):
# .env
PORT=4000
API_KEY=mysecretapikey123
Use dotenv in app file (e.g., index.js):
// index.js
require('dotenv').config();
const port = process.env.PORT;
const apiKey = process.env.API_KEY;
console.log('Server running on port:', port);
console.log('API Key:', apiKey);
Add .env to .gitignore to keep it out of version control:
# .gitignore
.env
Validating Request Body
Developers can use available open-source packages like Joi to ensure the request body is proper and does not contain any malicious content. We can validate all the request parameters and body parameters to meet the expected schema before executing actual logic.
Example :
Install Joi
Run the following command to install Joi:
npm install joi
Create a Joi Schema:
// User registration validation schema
const userSchema = Joi.object({
name: Joi.string().min(3).max(30).required(),
email: Joi.string().email().required(),
password: Joi.string().min(8).required(),
});
Use Linting Packages
Linters help you write code that is clean and consistent. ESLint is one of the most common linting tools for checking problems in code and it can also evaluate code styles to ensure that they satisfy best practices standards.
There are various programs available that automatically format and make code more readable . It also fixes small syntax problems, such as putting semicolons at the end of each statement.
Example:
Install ESLint and Prettier
Run the following command in our project directory to install ESLint and Prettier:
npm install eslint prettier --save-dev
Initialize ESLint
Create an ESLint configuration file by running:
npx eslint --init
Add Scripts to package.json
“scripts”: {
“lint”: “eslint .”
}
Don’t Use Callbacks, Instead Use Async Await
Async-await is supported in all node.js versions above Node 8 LTS. We can minimize the use of ‘callbacks’ and ‘promises’ to better deal with asynchronous code. It makes code look synchronous but in reality, it’s a non-blocking mechanism.
Example:
async function getDetails() {
try {
const response = await fetch('https://project/data');
const details= await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching :', error);
}
}
getDetails();
Using Arrow Functions (=>)
Using arrow functions in Node.js is recommended, particularly for generating compact and understandable code. Arrow functions are compact and great for short, simple functions.
const message = (name) => “Welcome,” + name + “.”;
Use of Strict Equality Operator (===)
Use the strict equality operator === instead of weaker abstract equality operator = ==. == will convert two variables to a common type then compare them while === doesn’t type case variables, and ensures that both variables are of the same type and equal.
Example
const a = 5;
const b = "5";
// Loose equality (==) allows type coercion:
console.log(a == b); // true, because "5" is converted to 5
// Strict equality (===) checks both type and value:
console.log(a === b); // false, because the types are different (number vs. string)
Make Sure Our App has Auto Reload
We can set our Node.js application to reload automatically after any change you make to the code while it is still in development. You can save time and effort by eliminating the need to often move between ourcode editor and terminal. You can use widely accessible tools like Nodemon, Livereload, Grunt, etc.
Example :
Install Nodemon as a development dependency:
npm install nodemon --save-dev
Modify the package.json file to add a script for running our app with Nodemon:
"scripts": {
"start": "node app.js",
"dev": "nodemon app.js"
}
Partition the Entire Program into Small Components
Maintaining a sizable code base puts the application at risk of slowing down when developers try to add new features. Instead, divide your code into components and give each one its folder or dedicated codebase.
The best option is to break down the entire stack into independent parts. Ensure these stacks don’t share files; each can consist of just a few files like an API, service, data access, test, etc. Separating component files will make our app more scalable.
Monitoring Node App
Node.js monitoring means tracing the code execution and reporting after adding code to your project. To understand the health of your app, you will need some pivotal information to track. You can monitor process ID, log management, request rate, resource usage, uptime, downtime, error rates, load average, and latency.
Use the Latest LTS Version:
Always use the latest LTS (Long Term Support) version of Node.js to benefit from stability and security updates.
Structure Our Project
A well-structured project is easy to maintain and scale. Here’s a simple structure that you can follow:
- src – contains our main application code.
- controllers – handle the logic for our app.
- models – define our data structures.
- routes – manage the different endpoints of our API.
- services – contain business logic.
- tests – contain all the test files.
- .env – stores our sensitive information variables
- .gitignore – specifies files to ignore in GIT.
- .package.json – keeps track of dependencies and scripts.
- README.md – description about our project.
Keep Dependencies Updated
Regularly update your dependencies to ensure you have the latest features and security fixes.
Use npm outdated to check for outdated packages.
npm outdated
Update packages:
npm update
By following all best practices , we are able to create robust and efficient Node Js applications that are easier to manage and maintain, helping you develop a strong foundation for future growth and improvements.