How to Use Redis for Caching in a Node.js Backend

When building backend applications, performance is very important. You want your app to respond quickly, even when handling many requests. One way to make your app faster is by using caching.
Caching means storing data temporarily so it can be reused quickly. Instead of asking the database every time, your app can get the data from the cache if it already has it.
In this blog, we will learn how to use Redis for caching in a Node.js backend. Redis is a very fast, in-memory data store. It is great for caching and works well with many backend frameworks.
If you’re learning backend development in a java full stack developer course, understanding Redis and caching will help you write faster and smarter applications.
Let’s start by learning what Redis is and why it’s useful.
What is Redis?
Redis stands for Remote Dictionary Server. It is an open-source, in-memory key-value store. It is exceptionally fast because it keeps data in memory, not on disk.
You can use Redis to:
- Store temporary data (like user sessions)
- Cache API responses
- Count visits to a website
- Create queues for tasks
Redis is simple but powerful. It supports many data types like strings, lists, hashes, and sets.
In this blog, we will concentrate on using Redis to cache data in a Node.js app to improve performance.
Why Use Caching?
Imagine you have a route that fetches data from a database or external API. If many users hit that route, your server and database might become slow.
Instead of fetching the same data every time, you can cache the result. The next time the route is called, your app sends the cached data quickly—no need to fetch again.
Benefits of caching:
- Faster response time
- Reduced database or API load
- Better user experience
- Saves bandwidth and processing power
Let’s now see how to use Redis for caching in a simple Node.js app.
Step 1: Set Up a Node.js App
First, make sure you have Node.js installed. Then, create a new project:
mkdir redis-cache-example
cd redis-cache-example
npm init -y
Install the required packages:
npm install express axios redis
- express: Web framework
- axios: To make HTTP requests (we’ll fetch data from an API)
- redis: Redis client for Node.js
If you’re already working on an app during your full stack developer classes, you can add Redis to it using these same steps.
Step 2: Install and Start Redis
To use Redis locally, install it on your computer:
On macOS (using Homebrew):
brew install redis
brew services start redis
On Ubuntu:
sudo apt update
sudo apt install redis-server
sudo systemctl start redis
You can test if Redis is working by running:
redis-cli ping
It should reply with PONG.
Step 3: Create a Simple API with Caching
We will now write a simple Express app that brings user data from an external API and caches it using Redis.
Here’s the code:
// index.js
const express = require(‘express’);
const axios = require(‘axios’);
const redis = require(‘redis’);
const app = express();
const PORT = 3000;
// Connect to Redis
const client = redis.createClient();
client.on(‘error’, (err) => {
console.log(‘Redis error: ‘, err);
});
// Middleware to connect Redis
client.connect();
// Route to get user data
app.get(‘/user/:id’, async (req, res) => {
const userId = req.params.id;
try {
// Check Redis cache first
const cachedData = await client.get(userId);
if (cachedData) {
console.log(‘Cache hit’);
return res.send(JSON.parse(cachedData));
}
// If not in cache, fetch from external API
console.log(‘Cache miss’);
const response = await axios.get(`https://jsonplaceholder.typicode.com/users/${userId}`);
const userData = response.data;
// Save in Redis (cache for 60 seconds)
await client.setEx(userId, 60, JSON.stringify(userData));
res.send(userData);
} catch (err) {
console.error(err);
res.status(500).send(‘Something went wrong’);
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
In this code:
- When the route /user/:id is called, the app checks Redis for cached data.
- If it exists (cache hit), it sends the cached result.
- If not (cache miss), it fetches from the external API, stores the result in Redis, and sends the response.
This speeds up future requests for the same user.
Step 4: Test the API
Run your server:
node index.js
Then open your browser or use Postman:
http://localhost:3000/user/1
The first request will be a cache miss (slow), and next requests will be cache hits (fast).
Try different user IDs to see how caching works.
If you’re learning backend development in a full stack developer course, building a project like this helps you understand how caching improves performance in real apps.
How Redis Stores Data
Redis stores data as key-value pairs. In our example:
- Key: 1
- Value: User data for user with ID 1
You can view data in Redis using the Redis CLI:
redis-cli
> keys *
> get 1
This shows the cached data inside Redis.
You can also delete keys manually:
> del 1
Setting Expiry Times
We used this line to set data with an expiry:
await client.setEx(userId, 60, JSON.stringify(userData));
This tells Redis to remove the data after 60 seconds. You can change the time based on your app’s needs.
- Short expiry: Use for fast-changing data
- Long expiry: Use for rarely updated data
Benefits of Redis in Node.js Apps
Here’s why Redis is great for caching:
- Very fast (in-memory)
- Easy to use with Node.js
- Supports key expiry (auto delete)
- Helps reduce database/API usage
- Scales well for large apps
Even big companies use Redis to manage caching and improve speed.
When to Use Redis Caching
Use Redis when:
- Your data doesn’t change often
- You call the same API or query many times
- You want to lower your database or server load
- You want faster responses for users
Examples:
- Product listings
- User profiles
- Trending content
- Search results
Avoiding Common Mistakes
- Don’t cache sensitive or personal data without encryption
- Set an expiry time to avoid storing old data forever
- Don’t use Redis as your only storage—it’s meant for temporary data
- Handle Redis failures—your app should still work even if Redis is down
Final Thoughts
Redis is a powerful and simple tool to make your Node.js backend faster. By caching data in memory, Redis helps you reduce wait times, lower server load, and improve user experience.
In this blog, we learned:
- What Redis is and why it’s useful
- How to set up Redis in Node.js
- How to cache API results
- How to view and manage data in Redis
If you’re building a project during your full stack developer course in hyderabad, adding Redis caching will make it more professional and efficient. It’s a great skill to learn and use in real-world applications.
Now it’s your turn—try Redis in your own app and enjoy the speed boost!
Contact Us:
Name: ExcelR – Full Stack Developer Course in Hyderabad
Address: Unispace Building, 4th-floor Plot No.47 48,49, 2, Street Number 1, Patrika Nagar, Madhapur, Hyderabad, Telangana 500081
Phone: 087924 83183
