How to Access Cache Data in Node.js ?
Last Updated :
20 Jun, 2024
Caching is an essential technique in software development that helps improve application performance and scalability by temporarily storing frequently accessed data. In Node.js, caching can significantly reduce database load, minimize API response times, and optimize resource utilization. This article will guide you through various methods to access and manage cache data in a Node.js application.
Introduction to Caching
Caching involves storing copies of data in a temporary storage location, or cache, to quickly access it upon subsequent requests. This approach minimizes the need to repeatedly retrieve data from a slower backend data store, such as a database or an external API.
Why Use Caching?
- Improved Performance: Cache reduces latency and accelerates data retrieval.
- Reduced Database Load: Caching reduces the frequency of database queries, leading to better resource utilization.
- Enhanced Scalability: Efficient caching helps applications handle increased loads without degrading performance.
- Cost Efficiency: Reducing the need for repeated data retrieval from costly resources like databases or external services can save operational costs.
Caching Strategies
- In-Memory Caching: Stores data in the application’s memory for fast access.
- Distributed Caching: Uses external cache services like Redis to store data, allowing multiple instances of an application to access the same cache.
- Persistent Caching: Stores cache data in a persistent storage system that survives application restarts.
- Building simple nodejs REST API using express.
Steps to Set Up Project
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Step 4: Install the necessary packages/libraries in your project using the following commands.
npm i express node-cache

Project structure:

The updated dependencies in package.json file will look like:
"dependencies": {
"express": "^4.19.2",
"node-cache": "^5.1.2"
}
Example: Create a file server.js in the directory with following code:
Node
// server.js
// Importing express module
const express = require('express')
// Creating an express object
const app = express()
// Starting server using listen function on port 8000
app.listen(8000, err => {
if(err)
console.log("Error while starting server")
else
console.log("Server has been started at port 8000")
})
app.get('/', (req, res)=>{
res.send('Home page !')
})
Step to Run Application:Â Run the application using the following command from the root directory of the project
node server.js
Output:Â Your project will be shown in the URL http://localhost:3000/

Home PageExample: Add following code at the end of server.js, Create a simple API that performs a costly operation to serve response
(To simulate an external API / Database query).
Node
// server.js
function heavyComputation(){
let temp = 0;
for(let i=0; i<100000; i++)
temp = (Math.random()*5342)%i;
return 123;
}
app.get('/api', (req, res)=>{
let result = heavyComputation();
res.send("Result: "+result);
})
Stop server by Ctrl+C and start again by node server.js. In the browser, open Network tab in Chrome Dev Tools and check time required to get response.

Approach for Implementing caching
- On API request, check if the cache has key already set using has(key) function
- If the cache has the key, retrieve the cached value by get(key) function and use it instead of performing operation again. (This saves time)
- If the cache doesn't have a key, perform the operations required, and before sending the response, set the value for that key so that further requests can be responded to directly through cached data.
Implement node-cache
Import Node-cache npm module and create a new NodeCache object
const NodeCache = require( "node-cache" );
const myCache = new NodeCache();
Node-cache has following major functions
- .set(key, val, [ ttl ]): Used to set some value corresponding to a particular key in the cache. This same key must be used to retrieve this value.
- .get(key):Used to get value set to specified key. It returns undefined, if the key is not already present.
- has(key): Used to check if the cache already has some value set for specified key. Returns true if present otherwise false.
Example: Final Code for accessing chache data using above module.
Node
// server.js
// Importing express module
const express = require('express')
// Importing NodeCache and creating a
// new object called myCache
const NodeCache = require('node-cache')
const myCache = new NodeCache()
// Creating an express object
const app = express()
// Starting server using listen
// function on port 8000
app.listen(8000, err => {
if(err)
console.log("Error while starting server")
else
console.log(
"Server has been started at port 8000")
})
app.get('/', (req, res)=>{
res.send('Home page !')
})
// Function to demonstrate heavy computation
// like API requests, database queries, etc.
function heavyComputation(){
let temp = 0;
for(let i=0; i<100000; i++)
temp = (Math.random()*5342)%i;
return 123;
}
app.get('/api', (req, res)=>{
// If cache has key, retrieve value
// from cache itself
if(myCache.has('uniqueKey')){
console.log('Retrieved value from cache !!')
// Serve response from cache using
// myCache.get(key)
res.send("Result: " + myCache.get('uniqueKey'))
}else{
// Perform operation, since cache
// doesn't have key
let result = heavyComputation()
// Set value for same key, in order to
// serve future requests efficiently
myCache.set('uniqueKey', result)
console.log('Value not present in cache,'
+ ' performing computation')
res.send("Result: " + result)
}
})
Explanation:
- Stop server by Ctrl+C and start again by node server.js.
- Reload the webpage once. This time computation is performed. It can be seen on console also
- Reload the webpage again. This time data is served from cache as seen on console.
- Further reloads will serve data from cache, thereby saving computations.

Note: The difference between response time is not significant here, since the computation is very less, however for large and scaled projects, it provides a massive performance boost.Â
For example, GeeksforGeeks also uses advanced caching mechanisms for various purposes to achieve efficiency. Â
Similar Reads
How to Access HTTP Cookie in Node.js ? Cookies are small pieces of data sent by a server and stored on the client side, typically in the user's browser. They are often used to maintain stateful information such as user sessions, preferences, or tracking data. In Node.js, accessing and managing cookies is a common requirement for building
3 min read
How to cache JSON data in Redis with NodeJS? To cache JSON data in Redis with Node.js, you can use the redis npm package along with JSON serialization and deserialization. Redis, an open-source, in-memory data store, is commonly used as a caching solution due to its high performance and flexibility. In this tutorial, we'll explore how to cache
3 min read
How to store single cache data in ReactJS ? Storing Data in a cache is an important task in web applications. We can cache some data into the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested. PrerequisitesReact JSCach
2 min read
How to get single cache data in ReactJS ? We can use cache storage using window cache and in React JS to get single cache data. We can get single cache data from the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested.
2 min read
How to Access the File System in Node.js ? In this article, we looked at how to access the file system in NodeJS and how to perform some useful operations on files. Prerequisite: Basic knowledge of ES6Basic knowledge of NodeJS NodeJS is one of the most popular server-side programming frameworks running on the JavaScript V8 engine, which uses
3 min read