0
0
Expressframework~5 mins

Why caching improves performance in Express

Choose your learning style9 modes available
Introduction

Caching stores data temporarily so your app can get it faster next time. This makes your app quicker and saves work.

When your app fetches the same data many times, like user profiles.
When your app calls slow services or databases repeatedly.
When you want to reduce the load on your server during high traffic.
When you want to speed up page loading for users.
When you want to save bandwidth by not sending the same data again.
Syntax
Express
app.use((req, res, next) => {
  const cachedData = cache.get(req.url);
  if (cachedData) {
    res.send(cachedData);
  } else {
    res.originalSend = res.send.bind(res);
    res.send = (body) => {
      cache.set(req.url, body);
      res.originalSend(body);
    };
    next();
  }
});
This example shows a simple middleware caching responses by URL.
You can use libraries like 'node-cache' or 'redis' for better caching.
Examples
This example caches data for a specific route to avoid repeated database calls.
Express
const cache = new Map();

app.get('/data', (req, res) => {
  if (cache.has('data')) {
    res.send(cache.get('data'));
  } else {
    const data = fetchDataFromDB();
    cache.set('data', data);
    res.send(data);
  }
});
This middleware caches all responses by URL automatically.
Express
app.use((req, res, next) => {
  const cached = cache.get(req.url);
  if (cached) {
    res.send(cached);
  } else {
    res.originalSend = res.send.bind(res);
    res.send = (body) => {
      cache.set(req.url, body);
      res.originalSend(body);
    };
    next();
  }
});
Sample Program

This Express app caches the response for the '/time' route. The first request sends the current time and caches it. Later requests get the cached time instantly, so the time shown does not change until the server restarts.

Express
import express from 'express';

const app = express();
const cache = new Map();

app.use((req, res, next) => {
  const cachedResponse = cache.get(req.url);
  if (cachedResponse) {
    res.send(cachedResponse);
  } else {
    res.originalSend = res.send.bind(res);
    res.send = (body) => {
      cache.set(req.url, body);
      res.originalSend(body);
    };
    next();
  }
});

app.get('/time', (req, res) => {
  const currentTime = new Date().toISOString();
  res.send(`Current time is: ${currentTime}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Caching can save time but may show old data if not refreshed.

Use cache expiration to keep data fresh.

Test caching carefully to avoid bugs with stale data.

Summary

Caching stores data to speed up repeated requests.

It reduces work for your server and makes apps faster.

Use caching wisely to balance speed and data freshness.