API Response Caching using apicache Middleware in Node.js
Last Updated : 02 Aug, 2024
APIs are a crucial part of modern web applications, providing the means for different software systems to communicate and exchange data. However, frequent API calls, especially to the same endpoints, can lead to increased server load, slower response times, and higher bandwidth usage. Caching is a strategy to mitigate these issues by storing copies of API responses and serving them instead of hitting the backend server repeatedly. This article explores how to implement API response caching in Node.js using the apicache
middleware.
What is apicache
?
apicache
is a simple and easy-to-use caching middleware for Express-based applications. It provides an efficient way to cache responses from your API endpoints, thus reducing server load and improving response times. By storing responses for a specified duration, apicache
ensures that repeated requests to the same endpoint can be served quickly from the cache without involving backend processing.
Benefits of Caching
- Improved Performance: Reduces latency by serving cached responses instead of making time-consuming API calls.
- Reduced Server Load: Decreases the number of requests hitting the server, leading to better resource utilization.
- Bandwidth Savings: Minimizes data transfer, especially beneficial for clients with limited bandwidth.
- Enhanced User Experience: Faster response times lead to a smoother user experience.
Approach
By using the API cache middleware, we will fetch data from the JSONplaceholder API and cache the API responses for a period of five minutes. API cache is an npm package that makes it easier to cache API responses for express and node.js applications. The responses will be backed up for a specific period of time, so if you request the same resource representation, the API endpoint will not be hit and the data will be retrieved from the cache instead.
In the following example, we will observe that the data is retrieved faster since it does not hit an API endpoint.
Environment Setup
Ensure that node.js is installed on your local machine, as well as Postman for API testing. If you haven't installed them yet, please follow these links.
- Node.js: https://nodejs.org/en/download/
- Postman: https://www.postman.com/downloads/
As an alternative to Postman, you can also use https://reqbin.com/ for API testing.
Installation Steps
Step 1: Initialize npm
Make a new project directory and head over to your terminal. Initialize npm by using the following command:
npm init -y
Initializing npm Step 2: Install Dependencies. Install the following packages :
- express: node.js framework
- axios: to send HTTP requests
- morgan: logs the requests
npm i express axios morgan
Installing the required packagesStep 3: Install the middleware for caching API responses. Install API cache package using the following command.
npm i apicache
Installing apicacheStep 4: Create an app.js file to write the code for caching. Firstly, we will import all the installed packages in the app.js file to use them in our project. We will then configure the middlewares, i.e., express, Morgan, and Apicache, and set up our server. We will fetch posts and users from the JSONplaceholder API and cache the routes for 5 minutes.
Project Structure:
Project StructureExample: Implementation to show response caching using apicache middleware in Node.js.
JavaScript const express = require('express'); const morgan = require("morgan"); const apicache = require("apicache"); const axios = require('axios'); // Create Express Server const app = express(); app.use(morgan('dev')); //configure apicache let cache = apicache.middleware //caching all routes for 5 minutes app.use(cache('5 minutes')) app.get('/', (req, res) => { const data = axios.get( 'https://jsonplaceholder.typicode.com/posts').then((response) => { res.send(response.data) }) }) app.get('/users', (req, res) => { const userData = axios.get( 'https://jsonplaceholder.typicode.com/users').then((response) => { res.send(response.data) }) }) app.listen(3000, function() { console.log("Server is running on port 3000"); })
Step to run the application: To run the node.js application, go to your terminal and write the following command.
node app.js
Output: By default, the application will run on port 3000. On your browser, you can access posts at localhost:3000 and users at localhost:3000/users.
Step to test the response time Send a GET request to localhost:3000 using Postman.
Output: Initially, you will see a long response time. If you send the GET request several times, you will notice that data is retrieved much faster than the initial response time due to response caching. When we request a resource for the first time, the data gets cached and on requesting it again, the cached data is returned instead of hitting the API endpoint, resulting in faster response times.
Similarly, send a GET request to localhost:3000/users
Output: After the response is cached, you will notice that the data is retrieved faster.
Similar Reads
Using Restify to Create a Simple API in Node.js
Restify is an npm package that is used to create efficient and scalable RESTful APIs in Nodejs. The process of creating APIs using Restify is super simple. Building a RESTful API is a common requirement for many web applications. Restify is a popular Node.js framework that makes it easy to create RE
6 min read
Handling Requests And Responses in Node.js
Node.js is a powerful JavaScript runtime for building server-side applications. It provides an efficient way to handle HTTP requests and responses using the built-in http module or frameworks like Express.js. Understanding HTTP Requests and ResponsesAn HTTP request is sent by a client (browser or AP
4 min read
Explain the concept of middleware in NodeJS
Middleware in NodeJS refers to a software design pattern where functions are invoked sequentially in a pipeline to handle requests and responses in web applications. It acts as an intermediary layer between the client and the server, allowing for modularization of request processing logic and enabli
2 min read
Implementing Csurf Middleware in Node.js
Csurf middleware in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSR
4 min read
How to skip a middleware in Express.js ?
If we want to skip a middleware we can pass parameters to the middleware function and decide based on that parameter which middleware to call and which middleware to not call. Prerequisite: express.js: To handle routing. Setting up environment and execution: Step 1: Initialize node project npm init
1 min read
Understanding Mongoose Middleware in Node.js
Mongoose is a powerful tool for Node.js developers working with MongoDB databases. It simplifies database interactions and allows developers to model data with schemas, perform CRUD operations, and more. One of Mongoose's most powerful features is its middleware system. In this article, we'll explai
7 min read
Next JS Middleware: Extending Functionality in Your Application
Middleware plays an important role in creating backend applications which are used to intercept incoming requests, perform actions, and modify responses before send to routing handlers. In this article, we will understand middleware in Next.js by creating an authentication middleware. PrerequisitesJ
4 min read
Creating a REST API Backend using Node.js, Express and Postgres
Creating a REST API backend with Node.js, Express, and PostgreSQL offers a powerful, scalable solution for server-side development. It enables efficient data management and seamless integration with modern web applications. This backend can do Query operations on the PostgreSQL database and provide
4 min read
How to pass variables to the next middleware using next() in Express.js ?
The following example covers how to pass variables to the next middleware using next() in Express.js. Approach: We cannot directly pass data to the next middleware, but we can send data through the request object. [Middleware 1] [Middleware 2] request.mydata = someData; -------> let dataFromMiddl
2 min read
Stock Market API Integration in Node.js
In this article, we are going to build a simple web application, in which we would learn how we can integrate a simple API with NodeJS and fetch data from the server using that API. Here, we will learn about what API is, how to get data from the Server using that API and all the stuff related to tha
15+ min read