5 ways to improve the performance of Node.js API
Tags: node, javascript, api, webdev
Published: 2022-11-18 16:23:51

Today, majority of the Applications you see around are API-Centric. An application that uses application programming interfaces (APIs) to communicate data with other apps is known as an API-centric application. The frontend and backend of this kind of program can communicate with one another.
Most of these API's are build using NodeJS because of its speed, ease of development, etc.

![API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v62w1qa228vejr1ci0wh.gif)
As a developer, I find it a high priority to ensure my API has the best performance. In this article, I will be showing you key tips to optimize the performance of your Node.js API

## Prerequisites
To be able get the best out of this article, You need to be familiar with the following:
- Node.JS
- How to develop an API using Node

## Let's get started.
NodeJS comes with a lot of packages in building applications. It sometimes becomes frustrating moving from one site to the other looking for implementations of such packages in your app. [askyourcode](https://askyourcode.com) is one powerful code search engine I use for such implementations. It helps you to search through a large codebase on how to implement a particular package or your personal codebase. You can check it out.
![gif](https://user-images.githubusercontent.com/3425038/193901565-b9d2feec-dbf9-4b29-9ea9-3b869a158a86.gif)

- **Use Asynchronous Functions**
Async functions are important functions used in JavaScript. In writing code the best you can do to optimize CPU usage is to write asynchronous functions to perform nonblocking I/O operations.
If you application heavily uses I/O operations, It becomes very important to make use of Async function. Async functions make it possible for the CPU to handle multiple operations at the same time.
- **Stateless Authentication**
stateless client-side authentication uses JSON Web Token (JWT), OAuth and other techniques which boosts application performance greatly. Every time a user logs into the website using this Stateless Authentication method, a web token is generated. It holds all the necessary user data, which is transmitted back to the appropriate user for each API request's authentication.
Avoid Sessions and Cookies in APIs, and Send Only Data in the API Response.

>  JWT is a JSON-based security token for API Authentication 
>  OAuth is not an API or a service – rather, it's an open standard for authorization. OAuth is a standard set of steps for obtaining a token

- **Error Handling middleware**
Whenever a server error occurs, [Express.js](https://expressjs.com) detects it and, unless you have your own custom error handler, uses its built-in error handler to send a response to the client with the error message. This built-in error handling by express can be sometimes harmful by exposing config information to your API users which can be dangerous when app is on production. Not only do custom error handlers handle errors properly but also to correctly empty away any unused resources when the application starts up again.
check out my article on [Custom Error Handlers](https://dev.to/qbentil/how-to-write-custom-error-handler-middleware-in-expressjs-using-javascript-29j1) for how to implement this.

- **Optimize Database Queries**
Data in a database can grow huge with time. During this period, you will realize your API takes a longer time to fetch data when requested. This is as a result of bad query. Bad queries can reduce the overall performance of your API.
_Example of a Bad Query_
```Users.find({email: 'sbentil@gmail.com'}).explain("executionStats")```
What makes a good Query? - INDEXING
Indexing is a technique for improving a database's performance by reducing the number of disk accesses necessary during query processing. It is a data structure method for finding and quickly accessing the data in a database. Several database columns are used to generate indexes.
_Example of a Good Query_

```
model.getCollection("user").createIndex({ "email": 1 }, { "name": "shadrack", "unique": true })
{
 "createdCollectionAutomatically" : false,
 "numIndexesBefore" : 1,
 "numIndexesAfter" : 2,
 "ok" : 1
}
```

- **Reduce latency via Caching**
One popular method for enhancing Node Js performance is caching. Both client-side and server-side web applications can use caching.
However, because it supports JavaScript, CSS sheets, HTML pages, and other features, server-side caching is the most popular option for improving Node.Js efficiency. Web applications typically use caching to speed up data retrieval.

In building API, caching can be done using [Redis](https://redis.io/)
Redis optimizes the APIs response time by storing and retrieving the data from the main memory of the server. It increases the performance of the database queries which also reduces access latency. 

## Conclusion
Happy Hacking!

Bentil here🚀
Which of the methods mentioned do you use already. Share your experience below. It might be helpful to someone else too. I will be glad to hear from you in the comment section.

If you find this content helpful, Please Like, comment and share