Applying caching to an API endpoint is improved performance and reduced server load.
I use caching only for GET api endpoints.
We use Redis tool for adding caching layer on the top of GET api endpoints.
- Install Redis using this link.
https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/
- Now install redis package in the project. Go to root folder and run this command in the terminal.
terminal
Copynpm install redis
- Create a file name cachingLayer.js in middleware folder and paste the following code.
JavaScript
Copyconst redisClient = require('../clients/redis'); // time in seconds const CACHING_TIME = 60; const cachingLayer = async (req, res, next) => { let key = `${req.originalUrl}` || req.url; res.setHeader('Content-Type', 'application/json'); const cachedData = await redisClient.get(key); if (cachedData) { res.send(JSON.parse(cachedData)); } else { res.sendResponse = res.send; res.send = (body) => { if (res.statusCode === 200) { // time is 60 seconds redisClient.set(key, JSON.stringify(body), 'EX', CACHING_TIME); } res.sendResponse(body); }; next(); } }; module.exports = cachingLayer;
- Navigate to the routes/publicRoutes.js file and import caching middleware. Apply this middleware to GET API route.
JavaScript
Copyconst cachingLayer = require('../middleware/cachingLayer'); router.get('/', restrictedRoute, cachingLayer, publicController.getSingleTodo);
Now, this route has a caching layer, so the data will be stored for 60 seconds. If you make an API call within the next 60 seconds, the data will be retrieved from the cached database (Redis). After that, subsequent API calls will fetch the latest data.