📖 Scenario: You are building a simple Express server that returns user profile data. To make the server faster, you want to add caching so repeated requests for the same user do not need to fetch data again.
🎯 Goal: Build an Express server that caches user profile data in memory to improve response speed for repeated requests.
📋 What You'll Learn
Create an object called userProfiles with 3 user profiles and their details
Create a cache object called cache to store fetched profiles
Write a function getUserProfile that checks the cache before returning a profile
Add an Express route /user/:id that uses getUserProfile to send the profile data
💡 Why This Matters
🌍 Real World
Caching is used in web servers to speed up responses by storing data temporarily, reducing database or API calls.
💼 Career
Understanding caching helps backend developers optimize performance and scalability of web applications.
Progress0 / 4 steps
1
Create user profile data
Create an object called userProfiles with these exact entries: 1 with name 'Alice' and age 30, 2 with name 'Bob' and age 25, and 3 with name 'Charlie' and age 35.
Express
Hint
Use an object with keys 1, 2, and 3. Each key maps to an object with name and age.
2
Add a cache object
Create an empty object called cache to store cached user profiles.
Express
Hint
Just create an empty object named cache.
3
Write the caching function
Write a function called getUserProfile that takes id as a parameter. It should check if cache[id] exists and return it if yes. Otherwise, get the profile from userProfiles[id], store it in cache[id], and return it.
Express
Hint
Use an if to check cache, else get from userProfiles and save to cache.
4
Add Express route using caching
Add an Express route /user/:id that uses getUserProfile to get the profile for req.params.id and sends it as JSON response. Use express() to create the app and listen on port 3000.
Express
Hint
Import Express, create app, add route with app.get, use getUserProfile, send JSON, and listen on port 3000.
Practice
(1/5)
1. Why does caching improve performance in an Express app?
easy
A. It slows down the server to handle more requests
B. It increases the size of the server's memory permanently
C. It stores data temporarily to avoid repeating expensive operations
D. It deletes old data to free up space immediately
Solution
Step 1: Understand caching purpose
Caching saves results of expensive operations temporarily so they can be reused.
Step 2: Relate caching to performance
By reusing stored data, the server avoids repeating slow tasks, speeding up responses.
Final Answer:
It stores data temporarily to avoid repeating expensive operations -> Option C
Quick Check:
Caching = Temporary storage for speed [OK]
Hint: Caching saves repeated work to speed up responses [OK]
Common Mistakes:
Thinking caching permanently increases memory
Believing caching slows down the server
Confusing caching with deleting data
2. Which Express middleware syntax correctly sets a simple cache header for 1 hour?
easy
A. res.cacheControl('3600')
B. res.set('Cache-Control', 'max-age=3600')
C. res.header('Cache-Control', 'no-cache')
D. res.cache('max-age=3600')
Solution
Step 1: Identify correct Express method
Express uses res.set() or res.header() to set headers; res.set() is common.
Step 2: Check cache header format
'Cache-Control' with 'max-age=3600' sets cache for 3600 seconds (1 hour).
Final Answer:
res.set('Cache-Control', 'max-age=3600') -> Option B
fetchData() is asynchronous and returns a Promise. What is the main issue?
medium
A. fetchData() blocks the server, causing timeout
B. cache.info is never set, causing infinite loop
C. res.send() cannot send strings
D. res.send() is called before fetchData() resolves, sending a Promise object
Solution
Step 1: Identify async function usage
fetchData() returns a Promise but code treats it as synchronous.
Step 2: Understand res.send() timing
res.send(data) runs immediately, sending the unresolved Promise, not actual data.
Final Answer:
res.send() is called before fetchData() resolves, sending a Promise object -> Option D
Quick Check:
Async function needs await before sending [OK]
Hint: Await async calls before sending response [OK]
Common Mistakes:
Ignoring async nature of fetchData()
Assuming cache is never set
Thinking res.send() can't send strings
5. You want to cache user profile data in Express but ensure it updates every 10 minutes. Which approach best balances caching and data freshness?
hard
A. Store data in cache with a timestamp; refresh cache if older than 10 minutes
B. Cache data forever without expiration to maximize speed
C. Never cache user data to always get fresh info
D. Clear cache manually only when server restarts
Solution
Step 1: Understand caching with expiration
To keep data fresh, cache should have a time limit after which it refreshes.
Step 2: Evaluate options for freshness and speed
Store data in cache with a timestamp; refresh cache if older than 10 minutes uses timestamp to refresh cache every 10 minutes, balancing speed and freshness.
Final Answer:
Store data in cache with a timestamp; refresh cache if older than 10 minutes -> Option A
Quick Check:
Timed cache refresh = Store data in cache with a timestamp; refresh cache if older than 10 minutes [OK]
Hint: Use timestamps to refresh cache periodically [OK]
Common Mistakes:
Caching forever causes stale data
Never caching loses speed benefits
Manual cache clearing is unreliable
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.