Optimizing Performance with Caching in Express.js
api
nodejs
cache
expressjs
servers
Caching is a common technique used to improve the performance of web applications by storing data in memory so that it can be quickly accessed without the need to retrieve it from a slower data store such as a database or API.
In this tutorial, we will learn how to implement server-side caching in an ExpressJS application using the node-cache package.
Prerequisites
Before we get started, make sure you have the following installed on your machine:
Node.js and npm
You should also be familiar with the basic concepts of web development, such as HTTP requests and responses, and the use of HTTP status codes.
Setting Up the Project
To get started, create a new project and install the express and node-cache packages:
mkdir caching-example
cd caching-example
npm init -y
npm install express node-cache axios
This will create a package.json file in your project directory with default values and install dependencies.
Setting Up the Server
Now, let’s create an index.js file in the root of our project and add the following code to set up an simple ExpressJS server:
const express = require('express');
const axios = require('axios');
const app = express();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
This code creates an ExpressJS app and sets up a route that listens for GET requests to the root path (’/’) and responds with a message of "Hello, World!".
To start the server, run the following command in your terminal:
node index.js
You should see the message “Server listening on port 3000” printed in the terminal.
Implementing Caching
Important: PUT, DELETE and POST methods should never be cached.
Now that we have a basic server set up, let’s implement caching using the node-cache package.
First, require the node-cache package at the top of your index.js file:
const NodeCache = require('node-cache');
Next, create a new cache instance:
const cache = new NodeCache();
We can now use the cache instance to store and retrieve data.
Let’s say we have a /products route that retrieves data from dummyjson API and we want to cache the results to improve performance. We can do this by using the get and set methods of the cache instance.
app.get('/products', async (req, res) => {
// Try to get the data from the cache
const data = cache.get('users');
// If the data is in the cache, return it
if (data) {
return res.json(data);
}
// Otherwise, retrieve the data from the API
const response = await axios.get('https://dummyjson.com/products');
const productsObj = response.data;
// Store the data in the cache for 1 hour
cache.set('users', productsObj, 3600);
// Then return the data to the client
res.json(productsObj);
});
This code uses axios to make a request to the dummyjson API and retrieve a list of products. It then stores the data in the cache using the set method and returns the data to the client.
If the data is already in the cache, it is retrieved using the get method and returned to the client without making a request to the API. This can significantly reduce the response time for subsequent requests and reduce the load on the server.
Setting the Cache Duration
By default, the cache duration is set to 0, which means that the data will never expire. You can specify a different duration by passing a number of seconds as the third argument to the set method, as shown in the example above.
For example, to set the cache duration to 1 day (86400 seconds), you can use the following code:
cache.set('users', json, 86400);
Full Code :
const express = require('express');
const NodeCache = require('node-cache');
const axios = require('axios');
const app = express();
const cache = new NodeCache();
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.get('/products', async (req, res) => {
// Try to get the data from the cache
const data = cache.get('users');
// If the data is in the cache, return it
if (data) {
return res.json(data);
}
// Otherwise, retrieve the data from the API
const response = await axios.get('https://dummyjson.com/products');
const productsObj = response.data;
// Store the data in the cache for 1 hour
cache.set('users', productsObj, 3600);
// Then return the data to the client
res.json(productsObj);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
Conclusion
In this tutorial, we learned how to implement server-side caching in an ExpressJS application using the node-cache package. We set up a basic server and then implemented caching using the get and set methods of the node-cache package.
We saw how caching can improve the performance of our application by reducing server response time and reducing the load on the server. By using the node-cache package, we can easily implement caching in our ExpressJS application and take advantage of these benefits.
I hope this tutorial was helpful and gave you a good understanding of how to use caching to improve the performance of your ExpressJS applications.
Additional Resources
node-cache documentation
ExpressJS documentation
Thank you for following along with this tutorial. I hope you found it helpful.
Read More