0
0
RedisHow-ToBeginner · 4 min read

How to Use Redis Cache in Node.js: Simple Guide

To use Redis cache in Node.js, first install the redis client package, then connect to the Redis server using createClient(). Use set() to store data and get() to retrieve cached values asynchronously.
📐

Syntax

Here is the basic syntax to connect to Redis and use cache commands in Node.js:

  • createClient(): Creates a Redis client to connect to the server.
  • connect(): Establishes the connection asynchronously.
  • set(key, value): Stores a value under a key in the cache.
  • get(key): Retrieves the value stored under the key.
javascript
const redis = require('redis');

async function useCache() {
  const client = redis.createClient();
  client.on('error', (err) => console.log('Redis Client Error', err));
  await client.connect();

  await client.set('key', 'value');
  const value = await client.get('key');
  console.log(value);

  await client.disconnect();
}

useCache();
Output
value
💻

Example

This example shows how to connect to Redis, cache a username, retrieve it, and print it to the console.

javascript
const redis = require('redis');

async function cacheExample() {
  const client = redis.createClient();

  client.on('error', (err) => console.log('Redis Client Error', err));

  await client.connect();

  // Store username in cache
  await client.set('username', 'alice123');

  // Retrieve username from cache
  const username = await client.get('username');
  console.log('Cached username:', username);

  await client.disconnect();
}

cacheExample();
Output
Cached username: alice123
⚠️

Common Pitfalls

Common mistakes when using Redis cache in Node.js include:

  • Not awaiting connect() before using commands, causing errors.
  • Forgetting to handle connection errors with event listeners.
  • Not disconnecting the client, which can keep the Node.js process running.
  • Using callbacks instead of async/await with the modern Redis client.
javascript
/* Wrong way: Missing await on connect() */
const redis = require('redis');
const client = redis.createClient();
client.connect(); // Missing await

client.set('key', 'value'); // May fail because connection not ready

/* Right way: Await connect() and handle errors */
async function correctUsage() {
  const client = redis.createClient();
  client.on('error', (err) => console.log('Redis Client Error', err));
  await client.connect();
  await client.set('key', 'value');
  const val = await client.get('key');
  console.log(val);
  await client.disconnect();
}
correctUsage();
Output
value
📊

Quick Reference

Here is a quick cheat sheet for Redis cache commands in Node.js:

CommandDescription
createClient()Create a new Redis client instance
connect()Connect to the Redis server asynchronously
set(key, value)Store a value under a key in the cache
get(key)Retrieve the value stored under a key
disconnect()Close the connection to Redis server
on('error', callback)Listen for connection or command errors

Key Takeaways

Always await client.connect() before running Redis commands.
Use async/await syntax with the modern redis client for clarity.
Handle errors by listening to the 'error' event on the client.
Remember to disconnect the client to free resources.
Use set() to cache data and get() to retrieve cached data.