Simple Redis Key-Value Store with Node.js and ioredis
📖 Scenario: You are building a simple key-value store using Redis and Node.js. This store will save user preferences like theme color and language settings.
🎯 Goal: Create a Node.js script that connects to Redis using ioredis, sets some user preference keys, retrieves them, and then closes the connection.
📋 What You'll Learn
Create a Redis client using ioredis
Set at least two keys with string values in Redis
Retrieve the values of those keys
Close the Redis connection properly
💡 Why This Matters
🌍 Real World
Redis is often used for fast caching and storing session data in web applications. This project shows how to connect and interact with Redis from a Node.js backend.
💼 Career
Knowing how to use Redis with Node.js is valuable for backend developers working on scalable web apps, improving performance by caching and quick data access.
Progress0 / 4 steps
1
Setup Redis Client
Create a Redis client by importing Redis from ioredis and instantiate it with new Redis() assigned to a variable called redis.
Redis
Hint
Use require('ioredis') to import Redis and create a new client instance.
2
Set User Preference Keys
Use the redis.set method to set two keys: 'user:1:theme' with value 'dark' and 'user:1:language' with value 'en'.
Redis
Hint
Call redis.set twice with the exact keys and values.
3
Retrieve User Preference Values
Use await redis.get to retrieve the values of 'user:1:theme' and 'user:1:language'. Assign them to variables theme and language respectively. Wrap this code inside an async function called main.
Redis
Hint
Define an async function and use await redis.get to get the values.
4
Close Redis Connection
Inside the main function, after retrieving the values, close the Redis connection by calling redis.quit(). Then call the main function at the end of the script.
Redis
Hint
Call await redis.quit() inside main and then call main() after the function.
Practice
(1/5)
1. What does the set method do in ioredis when used with Node.js?
easy
A. Stores a value with a specified key in Redis
B. Retrieves a value from Redis by key
C. Deletes a key-value pair from Redis
D. Connects to the Redis server
Solution
Step 1: Understand the purpose of set in Redis
The set method is used to store data by assigning a value to a key in Redis.
Step 2: Differentiate from other methods
get retrieves data, del deletes data, and connection is handled separately.
Final Answer:
Stores a value with a specified key in Redis -> Option A
Quick Check:
set stores data [OK]
Hint: Remember: set = save data, get = read data [OK]
Common Mistakes:
Confusing set with get
Thinking set deletes data
Assuming set connects to Redis
2. Which of the following is the correct syntax to get a value for key 'name' using ioredis with async/await?
easy
A. const value = redis.get('name');
B. const value = redis.getSync('name');
C. const value = await redis.set('name');
D. const value = await redis.get('name');
Solution
Step 1: Recognize async nature of ioredis commands
ioredis commands return promises, so await is needed to get the resolved value.
Step 2: Identify correct method and usage
get retrieves the value; set stores data; getSync does not exist.
Final Answer:
const value = await redis.get('name'); -> Option D
Quick Check:
Use await with get [OK]
Hint: Always use await with async Redis calls [OK]
Common Mistakes:
Omitting await causing unresolved promises
Using non-existent getSync method
Using set instead of get to read data
3. What will be the output of the following code snippet?
const Redis = require('ioredis');
const redis = new Redis();
async function test() {
await redis.set('color', 'blue');
const val = await redis.get('color');
console.log(val);
}
test();
medium
A. null
B. undefined
C. blue
D. SyntaxError
Solution
Step 1: Analyze the set command
The code stores the string 'blue' with key 'color' in Redis asynchronously.
Step 2: Analyze the get command and console output
The code retrieves the value for 'color' and logs it, which should be 'blue'.
Final Answer:
blue -> Option C
Quick Check:
set then get returns stored value [OK]
Hint: set then get returns stored value [OK]
Common Mistakes:
Forgetting await causing undefined output
Assuming get returns null if key exists
Syntax errors from missing async
4. Identify the error in the following code snippet using ioredis:
const Redis = require('ioredis');
const redis = new Redis();
function getValue() {
const value = redis.get('key');
console.log(value);
}
getValue();
medium
A. Missing await causing value to be a Promise
B. Incorrect Redis import statement
C. Redis client not connected
D. Using console.log inside function is invalid
Solution
Step 1: Understand async nature of redis.get
The get method returns a Promise, so without await, value is a Promise object.
Step 2: Identify missing await and its effect
Logging value prints a Promise, not the actual stored value.
Final Answer:
Missing await causing value to be a Promise -> Option A
Quick Check:
Always await async Redis calls [OK]
Hint: Always await redis.get to get actual value [OK]
Common Mistakes:
Ignoring async/await causing Promise logs
Thinking Redis import is wrong
Assuming console.log inside function is invalid
5. You want to store a user's session data as a JSON object in Redis using ioredis. Which approach correctly stores and retrieves the session data?
hard
A. Store session as multiple keys like set('session:user', user) and set('session:data', data)
B. Use set('session', JSON.stringify(session)) to store and JSON.parse(await get('session')) to retrieve
C. Use hmset('session', session) without stringifying and hgetall('session') to retrieve
D. Use set('session', session) directly and await get('session') to retrieve
Solution
Step 1: Understand Redis stores strings
Redis stores strings, so objects must be converted to strings before storing.
Step 2: Use JSON methods to store and retrieve objects
Use JSON.stringify to convert object to string before storing, and JSON.parse to convert back after retrieving.
Final Answer:
Use set('session', JSON.stringify(session)) to store and JSON.parse(await get('session')) to retrieve -> Option B
Quick Check:
Stringify before set, parse after get [OK]
Hint: Stringify objects before set, parse after get [OK]
Common Mistakes:
Trying to store objects directly without stringifying
Using hash commands without proper structure
Splitting session into multiple keys unnecessarily
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.