Open In App

API response caching using apicache middleware in Node.js

Last Updated : 25 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Caching simply means storing data. Caching API responses refer to holding copies of the requested response for a specific time to retrieve data faster. Whenever a client requests a resource, the request goes to the server holding that resource via the cache. In the request path, if the requested resource is present in the cache, it uses that copy instead of fetching the data from the server. Cached data returns as a response. Therefore, data is served more quickly and network performance is improved.   

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/
  • JSON Viewer Pro chrome extension: https://chrome.google.com/webstore/detail/json-viewer-pro/eifflpmocdbdmepbjaopkkhbfmdgijcc for visualizing the JSON response as a tree.

As an alternative to Postman, you can also use https://reqbin.com/ for API testing. 

Follow the steps below and get started. 

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 packages

Step 3: Install the middleware for caching API responses. Install API cache package using the following command.

npm i apicache 

Installing apicache

Step 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.

Add the following code to the app.js file. 

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");
})


Final Project Structure: 

Project Structure

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.

Output : Accessing the posts and users from the API

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. 

Testing Response Time 

Similarly, send a GET request to localhost:3000/users 

Output: After the response is cached, you will notice that the data is retrieved faster. 

Testing Response Time



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads