Redis client for TypeScript: ioredis and redis (node-redis)
In the world of modern web applications and microservices, Redis is one of the most popular in-memory data stores. It is used for caching, session management, task queues, Pub/Sub, and much more. If you are developing in TypeScript, you will need a reliable client to interact with Redis. In this article, we will look at two main options: ioredis and redis (also known as node-redis). Both libraries have excellent TypeScript support, are actively maintained, and provide a wide range of features.
Why do you need a Redis client for TypeScript?
TypeScript adds static typing to JavaScript, making code more predictable and reducing errors at the development stage. A Redis client for TypeScript allows you to:
- Work with Redis commands with full type support.
- Use autocompletion in the IDE (IntelliSense).
- Easily integrate with modern frameworks (NestJS, Express, Koa).
- Simplify error handling and reconnections.
The ioredis library
ioredis is a full-featured Redis client that has long been the de facto standard in the Node.js ecosystem. It supports clustering, Pub/Sub, pipelining, transactions (MULTI/EXEC), automatic reconnection, and much more. ioredis is written in TypeScript and provides types out of the box.
Installation
npm install ioredisnpm install @types/ioredis # if you are using TypeScript < 4.0Connection and basic operations example
import Redis from 'ioredis';
// Create a connection to Redis (default localhost:6379)const redis = new Redis();
// Async function for demonstrationasync function demo() { try { // Setting a value await redis.set('user:1:name', 'Anna'); await redis.set('user:1:age', 30);
// Getting a value const name = await redis.get('user:1:name'); console.log('User name:', name);
// Working with hashes await redis.hset('user:2', 'name', 'Ivan', 'age', 25); const user2 = await redis.hgetall('user:2'); console.log('User 2:', user2);
// Increment const views = await redis.incr('page:home:views'); console.log('Page views:', views);
// Setting with expiration (TTL) await redis.setex('temp:code', 60, '123456'); const ttl = await redis.ttl('temp:code'); console.log('Remaining key TTL:', ttl, 'sec');
} catch (error) { console.error('Redis error:', error); } finally { // Close the connection redis.disconnect(); }}
demo();Cluster and Pub/Sub support
ioredis works great with Redis clusters. A special Cluster class is used for this:
import Redis from 'ioredis';
const cluster = new Redis.Cluster([ { host: '127.0.0.1', port: 7000 }, { host: '127.0.0.1', port: 7001 }, { host: '127.0.0.1', port: 7002 }]);
await cluster.set('foo', 'bar');const value = await cluster.get('foo');console.log(value); // 'bar'For Pub/Sub, a separate connection is used, as a subscriber cannot execute regular commands:
import Redis from 'ioredis';
const subscriber = new Redis();const publisher = new Redis();
subscriber.subscribe('news', (err, count) => { console.log(`Subscribed to ${count} channel(s)`);});
subscriber.on('message', (channel, message) => { console.log(`Received message from channel ${channel}: ${message}`);});
// Publishing a messagepublisher.publish('news', 'Hello from TypeScript!');The redis library (node-redis)
redis (the redis package on n