What if your app could remember answers and skip slow database trips every time?
Why In-memory caching with node-cache in Express? - Purpose & Use Cases
Imagine your Express app fetching the same data from a database every time a user requests it, even if the data hasn't changed.
This repeated fetching slows down responses, wastes server resources, and can overwhelm your database when many users visit at once.
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.
app.get('/data', (req, res) => { db.query('SELECT * FROM items', (err, data) => { res.send(data); }); });
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); }); });
This lets your app respond faster and handle more users smoothly by reducing repeated work.
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.
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.
Practice
node-cache in an Express app?Solution
Step 1: Understand what caching means
Caching means storing data temporarily to avoid repeated slow operations.Step 2: Identify node-cache role in Express
node-cache stores data in memory temporarily to speed up data retrieval.Final Answer:
To temporarily store data in memory for faster access -> Option BQuick Check:
In-memory caching = temporary fast storage [OK]
- Confusing cache with permanent database storage
- Thinking node-cache handles authentication
- Assuming node-cache serves static files
node-cache?Solution
Step 1: Recall node-cache import and usage
node-cache is imported as NodeCache and instantiated with new keyword.Step 2: Check syntax correctness
Correct syntax is: const cache = new NodeCache();Final Answer:
const cache = new NodeCache(); -> Option CQuick Check:
Use new NodeCache() to create cache [OK]
- Calling nodeCache.create() which does not exist
- Using lowercase 'nodeCache' instead of 'NodeCache'
- Omitting 'new' keyword when creating instance
/data twice quickly?const express = require('express');
const NodeCache = require('node-cache');
const app = express();
const cache = new NodeCache();
app.get('/data', (req, res) => {
const cached = cache.get('myData');
if (cached) {
res.send('From cache: ' + cached);
} else {
const freshData = 'Hello World';
cache.set('myData', freshData, 10);
res.send('Fresh data: ' + freshData);
}
});
app.listen(3000);Solution
Step 1: Analyze cache check on first request
Cache is empty initially, so first request sets and returns fresh data.Step 2: Analyze cache check on second request
Second request finds data in cache and returns cached data.Final Answer:
First request: Fresh data: Hello World; Second request: From cache: Hello World -> Option AQuick Check:
Cache empty first, then hit cache second [OK]
- Assuming cache is always empty
- Thinking cache returns fresh data every time
- Mixing order of fresh and cached responses
node-cache in Express:const NodeCache = require('node-cache');
const cache = NodeCache();
app.get('/item', (req, res) => {
const item = cache.get('itemKey');
if (!item) {
cache.set('itemKey', 'value');
res.send('Set new item');
} else {
res.send('Cached item: ' + item);
}
});Solution
Step 1: Check cache instance creation
node-cache requires 'new NodeCache()' to create an instance.Step 2: Identify missing 'new' keyword
Code uses 'NodeCache()' without 'new', causing error.Final Answer:
Missing 'new' keyword when creating cache instance -> Option DQuick Check:
Always use 'new' with NodeCache [OK]
- Forgetting 'new' keyword
- Thinking cache.set needs callback
- Assuming cache keys must be special format
node-cache. Which code snippet correctly sets the cache with expiration and retrieves it safely in Express?Solution
Step 1: Understand TTL unit in node-cache
TTL (time to live) is in seconds, so 5 minutes = 300 seconds.Step 2: Check correct usage of set and get
cache.set(key, value, ttl) sets with expiration; cache.get(key) retrieves value.Final Answer:
cache.set('user1', profile, 300); const data = cache.get('user1'); if (data) res.send(data); else res.send('No cache'); -> Option AQuick Check:
TTL in seconds, set with 300 for 5 minutes [OK]
- Using TTL in milliseconds instead of seconds
- Passing TTL to get() method incorrectly
- Setting TTL too low (5 seconds instead of 300)
Ready to prove it?
Pass the test and this pattern moves unknown
