CACHING IN NODEJS
Caching is essentially a layer of abstraction that works with a backend system (in our example, Node. js) and, often, a conventional database. It requires an intermediate storage mechanism. The goal is to make data retrieval more effective, and caching solutions are tailored for that specific objective.
Caching is an effective way to improve the performance of a Node.js Express API by reducing the amount of time it takes to generate a response.
There are several ways to implement caching in an Express API. Here are some common techniques:
Here’s an example of how to implement in-memory caching using the “memory-cache” package:
const express = require('express');
const cache = require('memory-cache');
const app = express();
const PORT = process.env.PORT;
app.get('/api/data', (req, res) => {
const data = cache.get('data');
if (data) {
console.log('Serving from cache');
return res.json(data);
} else {
console.log('Serving from API');
const newData = // fetch data from API
cache.put('data', newData, 60 * 1000); // cache for 1 minute
return res.json(newData);
}
});
app.listen(PORT, () => {
console.log(`API server started on port ${PORT}`);
});
In this example, the API endpoint “/api/data” checks if the data is available in the cache. If it is, it serves the response from the cache, otherwise, it fetches the data from the API and caches it for 1 minute using the “memory-cache” package. This technique can be used for any API endpoint that returns frequently accessed data that doesn’t change frequently.
Recommended by LinkedIn