Caching API Responses in Node.js with Redis

Tobechi DuruTobechi Duru
2 min read

Introduction

APIs often fetch data from databases or third-party services, which can be slow or resource-heavy. One way to make your application faster is by caching frequently requested data. In this article, we will build a small Node.js API with Express and Redis to demonstrate how caching improves performance.


Project Setup

We will create a simple API that returns user data. Instead of hitting the database every time, we will store responses in Redis.

Folder structure:

node-redis-cache-api/
│   package.json
│   server.js
│   README.md
└── routes/
    └── users.js

Step 1: Initialize Project

mkdir node-redis-cache-api && cd node-redis-cache-api
npm init -y
npm install express redis

Step 2: Create the Server

server.js

const express = require('express');
const app = express();

app.use(express.json());

// Routes
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);

// Root route
app.get('/', (req, res) => {
  res.json({
    message: 'Welcome to Node Redis Cache API',
    endpoints: ['/users']
  });
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

Step 3: Users Route with Redis Caching

routes/users.js

const express = require('express');
const router = express.Router();
const redis = require('redis');

// Create Redis client
const client = redis.createClient();

client.connect().catch(console.error);

const fakeDB = [
  { id: 1, name: 'Alice', role: 'Engineer' },
  { id: 2, name: 'Bob', role: 'Designer' }
];

// Middleware to check cache
async function checkCache(req, res, next) {
  const { id } = req.params;
  const data = await client.get(id);

  if (data) {
    return res.json({ fromCache: true, user: JSON.parse(data) });
  }
  next();
}

// Get user by ID
router.get('/:id', checkCache, async (req, res) => {
  const { id } = req.params;
  const user = fakeDB.find(u => u.id == id);

  if (!user) {
    return res.status(404).json({ message: 'User not found' });
  }

  // Save in cache
  await client.set(id, JSON.stringify(user), { EX: 30 }); // expire in 30s
  res.json({ fromCache: false, user });
});

module.exports = router;

Step 4: Testing the API

Run:

node server.js

Test endpoints:

  • GET /users/1 → Returns user (first call from DB, second call from cache).

  • GET /users/2 → Same logic.

You’ll notice the second request is faster because it comes from Redis.


Why This Matters

Caching is a real-world performance optimization technique. This approach reduces database load, speeds up API responses, and can be expanded to handle larger datasets. Even a simple caching layer like this demonstrates awareness of backend scalability and architecture.


Conclusion

By integrating Redis with a Node.js API, you can significantly improve response times. This concept applies to any large-scale system where performance matters.

1
Subscribe to my newsletter

Read articles from Tobechi Duru directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tobechi Duru
Tobechi Duru

Software Engineer, MERN-Stack Developer