Introduction to Redis and Node.js Integration

Explore Redis, start a server with Docker, and read and write data from Node.js.

🎯 Introduction

By the end of this article, you will understand what Redis is, where it fits, and how to write and read data from Node.js.


🧱 What Is Redis?

Redis is a key-value database that primarily reads and writes data in memory. It stores data and provides commands to read, modify, and delete it. Fast memory access makes Redis useful for workloads that read and write data frequently.

Key-value storage means looking up a value by its key. The key identifies the data; the value is its contents. Redis operations typically start with a known key.

Redis values support more than text: they can also be hashes, lists, sets, and other data structures. Each structure provides its own operations, such as updating a field, appending an element, or sorting by score. Applications do not have to retrieve and process the entire value each time.

Redis runs as a separate service. Node.js connects through a client, sends commands, and receives results. Multiple application processes can access the same Redis data. Redis also supports expiration and persistence to disk for recovery after a restart; how much data can be recovered depends on the persistence configuration.


💡 Common Uses for Redis

With the storage model in mind, consider these common uses:

Use caseRedis's role
Data cachingTemporarily store frequently requested results to reduce repeated database queries
Login sessionsStore server-side session records so application instances can share login state
Request counting and rate limitingCount requests to support limits over a time window
LeaderboardsStore members and scores, and retrieve rankings by score
NotificationsPublish and receive messages between programs

A cache is a temporary copy of data kept for reuse. When the copy is missing, the data can be fetched again from its original source. Caching is one common Redis use case; Redis also supports the other capabilities listed above.


⚖️ Redis and MySQL Compared

AspectRedisMySQL
Data organizationAccess strings, sets, and other structures by keyOrganize data into tables, rows, and columns
Typical queriesUse commands for keys or specific structuresFilter, join, and aggregate with SQL
StoragePrimarily operates in memory, with configurable persistencePrimarily designed for persistent disk storage, with in-memory caches

Choose based on access patterns and reliability requirements. Queries involving joins across tables still call for a relational database such as MySQL.

The browser calls a Node.js endpoint, and the backend accesses Redis. Do not expose the Redis connection address or password to the frontend.


🛠 Install Redis with Docker

Complete the Docker setup and start Docker first. This course uses Redis 7.4.2, Node.js 22.9.0, and version 5.9.0 of the redis npm package for reproducible exercises. These are not necessarily the latest versions.

Start the practice instance in your terminal:

docker run -d --name redis-course \
    -p 127.0.0.1:6379:6379 \
    redis:7.4.2 redis-server --save "" --appendonly no

6379 is the Redis server port; binding to 127.0.0.1 restricts access to your machine. --save "" and --appendonly no disable persistence for this exercise, where losing data after shutdown is acceptable. The persistence article uses separate instances.

This local practice environment has no authentication. Do not change the port mapping to expose it publicly. The security article covers production accounts and network configuration.

🧰 Install the Node.js redis Client and Connect

The client sends JavaScript calls to Redis. Using Node.js 22.9.0, install redis 5.9.0 in your practice directory:

mkdir redis-course
cd redis-course
npm install --save-exact redis@5.9.0

Create redis.mjs. Later articles reuse this file:

redis.mjs
import { createClient } from 'redis';

export const redis = createClient({
    url: process.env.REDIS_URL ?? 'redis://127.0.0.1:6379',
    disableOfflineQueue: true,
    socket: { connectTimeout: 1000, reconnectStrategy: false },
});

redis.on('error', error => console.error('Redis connection error:', error.message));

url is the connection address, which REDIS_URL can override. connectTimeout limits connection attempts to 1000 milliseconds. For now, automatic reconnection is disabled and new commands fail while disconnected so the script does not wait indefinitely. The connection management article covers production reconnection strategies.

Create hello.mjs, import the client, and connect:

hello.mjs
import { redis } from './redis.mjs';

await redis.connect();

Importing the module only creates the client object. Commands can run after connect() completes. The error listener logs connection errors; individual commands can still fail, so it does not replace error handling at the call site.


💡 Your First Reads and Writes with set() and get()

Append the following blocks to hello.mjs in order. First, write some text:

hello.mjs
const result = await redis.set('course:hello', 'Hello Redis');
console.log(result);

The output is OK, indicating a successful write. The first argument is the key; the second is the text value.

Read the value using the same key:

hello.mjs
console.log(await redis.get('course:hello'));

The output is Hello Redis. Reading a missing key returns null.

This script runs once, so close the connection before it exits:

hello.mjs
await redis.close();

Save both files and run:

node hello.mjs

The terminal prints OK followed by Hello Redis. See the node-redis connection documentation for connection options.


❓ Questions and Answers

Q1: Why start a Docker container after installing the redis npm package?

The npm package is only a client. The Redis server running in the container stores the data.

Q2: What should I check first for ECONNREFUSED?

Check whether the container is running, then check the connection address and mapped port. If the container is stopped, start the existing container:

docker start redis-course

Q3: Does restarting Redis always lose all data because it is in memory?

That depends on persistence configuration. See the persistence article for storage and recovery details.


🧪 Exercise

Replace the text with your own greeting, then read a key you have never written. Compare the results.

// Write your code here

🎉 You have connected Redis to Node.js and completed your first reads and writes!