One of the things that affect how users interact with our applications is its speed. Even though some users generally have a poor connection, they are expecting some minimum level of speed when using the application. To give our users a seamless experience, we are going to consider the possibility of optimizing our requests in node by using the concept of caching.
Trust me, your users will thank you.
In this article, we are going to look at how to optimize requests in our Node applications by caching responses to requests. Now, you may be wondering what caching is all about. Caching generally involves storing and retrieving data from a high-performance memory
Why Use A Cache
The goal of caching is to save your server the stress of having to do the same thing over and over again that results in the same output. Let’s take for example, you have a page that generates a report of a companies inventory for the previous day for accountability. Now, let’s imagine that the report page will be viewed at least a thousand times daily by different auditors. Generating a single report wouldn’t be a problem, but if the same report is going to be generated every single time a thousand times, then you need to look for a better way to do it and that’s where caching comes in.
Requirements
To enable you to follow through the article, you need to have the following :
- Node installed on your machine,
- Node Package Manager ( NPM ) installed on your machine
- Some Basic Javascript Knowledge
To confirm your installations, run the following in your terminal :
If you get version numbers as result, then you’re good to go.
Building A Basic Inventory Application
We need to make a simple inventory reporting application to test caching capabilities with. The main goal is to look at the different approaches to caching in our node applications.
Since you already have npm installed on your machine, create a new project folder and install the necessary packages :
Let’s take a look at the index.js.
Import express and sqlite:
express is a routing framework for Node which simplifies HTTP task. sqlite3 will power the database for this app. The application port is also specified and an express application is created.
Next thing we need to do is to create the server route. Just one route that points to a /products endpoint: