Cache Your Express NodeJS API

Muhammad Taif Khan
3 min readNov 17, 2022

--

CACHE YOUR NODEJS API

A cache is a storage location where data can be stored for quick and easy access. Caches are used in a variety of applications, including computers, web browsers, and web servers.

When data is stored in a cache, it is stored in a temporary location so that it can be quickly accessed.

Caching is important because it helps improve the speed and performance of a system.

When data is cached, it can be quickly accessed, which reduces the amount of time that a system must wait for data to be retrieved from the main memory.

In this tutorial, you will learn how to cache your NodeJs Express API, so it can reduce server load each time you send a request to your server.

So if you send multiple requests to the same API path (eg. “user1/posts/1”) in a determined amount of time.

The first time you hit that path the data will be fetched from the server and then the data will be stored in cache memory.

Read this 44-page book to fully understand the basics of API Development. You will never regret reading this Book

So next time if you again send a request to the same API path the data will be fetched from the cache storage rather than the server, and This will enhance the user experience and your data will load a lot faster than before. Now without further ado, Let’s get started…

First, we will install two NodeJs packages, one for creating an API and another for caching the API.

  1. But before installing packages, let’s initialize an empty Nodejs Project and create our app’s entry point:
npm init -y

2. Now create an index.js file in your project root folder

3. Run the following command in VS Code terminal:

npm install express, apicache 

4. After installing our packages let’s setup our Express API:

File: (index.js)

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
res.send('Hello World!')
})

app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

5. Now that we have set up our API, let’s move to the last and most important part of the app which is caching our API.

First, we will import our apicache package, and then we will access its middleware which we can use later on to manipulate each request and cache it.

File: (index.js)

const express = require('express');
const apicache = require('apicache');
const app = express();
let cache = apicache.middleware;
const port = 3000;

app.get('/', (req, res) => {
res.send('Hello World!')
})

app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

In the code above we imported the apicache module and accessed its middleware. we can cache our API in two ways.

One is to cache each route separately and the second is to cache all API routes. I will show you both.

In order to cache the API, we will call the cache middleware function as follows:

cache(“[time unit]”)

time: can be any number

unit: can be seconds, minutes, hours, or days

The time will determine how long we want to keep the response of a request in cache storage.

Cache a single Route:

File: (index.js)

const express = require('express');
const apicache = require('apicache');
const app = express();
let cache = apicache.middleware;
const port = 3000;

//here we cached our home route only
app.get('/', cache('5 minutes'), (req, res) => {
res.send('Hello World!')
})

app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

Cache all Routes:

File: (index.js)

const express = require('express');
const apicache = require('apicache');
const app = express();
let cache = apicache.middleware;
const port = 3000;

//here we cached all routes
app.use(cache('5 minutes'));

app.get('/',(req, res) => {
res.send('Hello World!')
})

app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})

and we are done…

To read more about apicache click the link.

Thanks for being with me till the end, hope it will help you in your next project.

URDU | HINDI VIDEO VERSION OF THE ARTICLE

CACHE YOUR EXPRESS NODEJS API — URDU|HINDI

To read more articles like this one Follow me.

Support me By Buying me a Coffee

Follow me on:

👨‍💻Github: https://github.com/Muhammad-Taif-Khan

🔗Twitter: https://twitter.com/MTKTheOfficial

📰My Newsletter: https://www.getrevue.co/profile/MuhammadTaifKhan

--

--

Muhammad Taif Khan

S/W Dev | Freelancer | Loves writing about Programming and sometimes money making | Support me? https://www.buymeacoffee.com/muhammadtaif