0
0
Expressframework~3 mins

Why In-memory caching with node-cache in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your app could remember answers and skip slow database trips every time?

The Scenario

Imagine your Express app fetching the same data from a database every time a user requests it, even if the data hasn't changed.

The Problem

This repeated fetching slows down responses, wastes server resources, and can overwhelm your database when many users visit at once.

The Solution

Using in-memory caching with node-cache stores data temporarily in your server's memory, so repeated requests get fast answers without hitting the database each time.

Before vs After
Before
app.get('/data', (req, res) => { db.query('SELECT * FROM items', (err, data) => { res.send(data); }); });
After
const NodeCache = require('node-cache');
const cache = new NodeCache();
app.get('/data', (req, res) => {
  const cached = cache.get('items');
  if (cached) return res.send(cached);
  db.query('SELECT * FROM items', (err, data) => {
    if (err) return res.status(500).send('Database error');
    cache.set('items', data, 60);
    res.send(data);
  });
});
What It Enables

This lets your app respond faster and handle more users smoothly by reducing repeated work.

Real Life Example

Think of a news website showing the latest headlines; caching them means visitors get instant updates without the server reloading the same news for every person.

Key Takeaways

Manual repeated data fetching slows down apps and wastes resources.

In-memory caching stores data temporarily for quick reuse.

Node-cache makes caching easy and improves app speed and scalability.