Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • NodeJS Tutorial
  • NodeJS Exercises
  • NodeJS Assert
  • NodeJS Buffer
  • NodeJS Console
  • NodeJS Crypto
  • NodeJS DNS
  • NodeJS File System
  • NodeJS Globals
  • NodeJS HTTP
  • NodeJS HTTP2
  • NodeJS OS
  • NodeJS Path
  • NodeJS Process
  • NodeJS Query String
  • NodeJS Stream
  • NodeJS String Decoder
  • NodeJS Timers
  • NodeJS URL
  • NodeJS Interview Questions
  • NodeJS Questions
  • Web Technology
Open In App
Next Article:
Implementing Csurf Middleware in Node.js
Next article icon

API Response Caching using apicache Middleware in Node.js

Last Updated : 02 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Project Structure: 

Project Structure

Example: 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. 


Next Article
Implementing Csurf Middleware in Node.js

R

riyaa7vermaa
Improve
Article Tags :
  • Web Technologies
  • Node.js
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • NodeJS-Questions

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences