Caching in Node.js can significantly improve our app’s performance, reducing the load on our server and database by storing frequently accessed data in memory or external caching layers. There are multiple ways to do caching in Node.js but in this post we will learn how to do caching using node-cache.

Step 1 :

Install node-cache package in your application by running the following command in your terminal.

npm i node-cache

Step 2 :

Use node-cache in your application for caching as shown below.

const express = require( "express" );
const Order = require( "./models/orderModel" ); //Order Model
const NodeCache = require( "node-cache" );
const myCache = new NodeCache( );
  
const app = express( );

const PORT = 3000;

app.listen( PORT, err => { 
    if( err ){
        console.log( err );
    }
    else {
        console.log( `Server has been started at port ${PORT}` );
    }
} );

app.get( "/", ( req, res ) => {
    res.send( "Welcome to home page !" );
} );



app.get( "/api/orders", async( req, res ) => {
    let orders = [ ];
    const key = "allOrders";

    if( myCache.has( key ) ){
        orders = JSON.parse( myCache.get( key ) );
    } else {
        orders = await Order.find( {} ); //Logic to fetch order data from database
        
        myCache.set( key, JSON.stringify( orders ) );
    }

    return res.status(200).json(
        {
            success: true,
            orders,
        }
    );
} );