How to use redis with node.js
Tags: programming, javascript, node, typescript
Published: 2024-01-31 13:20:51

Redis is a fast and efficient in-memory key-value store that can be used for various purposes, such as caching, message brokering, session management, and more. In this post, I will show you how to connect your Node.js application to a Redis database using the node-redis module, and how to perform some basic operations with Redis data structures.

## Prerequisites 

Before we start, you need to have Node.js and Redis installed on your system. You can follow the instructions on the official websites to install them: 

- [Node.js](^1^)
- [Redis](^2^) 

You also need to install the node-redis module, which is a modern and high-performance Redis client for Node.js. You can install it using npm: 

```bash
npm install redis
```

## Connecting to Redis 

To connect to Redis, you need to create a Redis client object using the `createClient` method of the node-redis module. You can pass an optional configuration object to specify the connection details, such as the host, port, username, password, and TLS options. By default, the client will connect to localhost on port 6379. 

Here is an example of creating a Redis client and connecting to a local Redis server: 

```javascript
// Import the node-redis module
const { createClient } = require('redis'); 

// Create a Redis client object
const client = createClient(); 

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

// Connect to Redis
client.connect()
  .then(() => console.log('Connected to Redis'))
  .catch(err => console.log('Failed to connect to Redis', err));
``` 

You can also use the `url` option to pass a connection string in the format `redis[s]://[[username][:password]@][host][:port][/db-number]`. For example: 

```javascript
// Create a Redis client object with a connection string
const client = createClient({
  url: 'redis://alice:foobared@localhost:6379'
});
``` 

To check if the client is connected and ready to send commands, you can use the `isReady` property, which returns a boolean value. You can also use the `isOpen` property, which returns true when the client's underlying socket is open, and false when it is not (for example, when the client is still connecting or reconnecting after a network error). 

## Working with Redis Data Structures 

Redis supports various data structures, such as strings, lists, sets, hashes, and more. You can use the node-redis module to store and retrieve data using these data structures. The module provides methods for each Redis command, and you can use them with either callbacks or promises. 

Here are some examples of using the node-redis module to work with Redis data structures: 

### Strings 

Strings are the simplest and most basic data type in Redis. You can store and retrieve strings using the `set` and `get` commands. For example: 

```javascript
// Store a string
client.set('foo', 'bar')
  .then(res => console.log(res)) // OK
  .catch(err => console.log(err)); 

// Retrieve a string
client.get('foo')
  .then(res => console.log(res)) // bar
  .catch(err => console.log(err));
```


### Lists 

Lists are ordered collections of strings. You can store and retrieve lists using commands such as `lpush`, `rpush`, `lpop`, `rpop`, `lrange`, and more. For example: 

```javascript
// Store a list
client.lpush('colors', 'red', 'green', 'blue')
  .then(res => console.log(res)) // 3
  .catch(err => console.log(err)); 

// Retrieve a list
client.lrange('colors', 0, -1)
  .then(res => console.log(res)) // [ 'blue', 'green', 'red' ]
  .catch(err => console.log(err));
``` 

### Sets 

Sets are unordered collections of unique strings. You can store and retrieve sets using commands such as `sadd`, `srem`, `smembers`, `sismember`, and more. For example: 

```javascript
// Store a set
client.sadd('fruits', 'apple', 'banana', 'orange')
  .then(res => console.log(res)) // 3
  .catch(err => console.log(err)); 

// Retrieve a set
client.smembers('fruits')
  .then(res => console.log(res)) // [ 'apple', 'banana', 'orange' ]
  .catch(err => console.log(err));
``` 

### Hashes 

Hashes are maps of fields and values. You can store and retrieve hashes using commands such as `hset`, `hget`, `hgetall`, `hdel`, and more. For example: 

```javascript
// Store a hash
client.hset('user', 'name', 'Alice', 'age', 25)
  .then(res => console.log(res)) // 2
  .catch(err => console.log(err)); 

// Retrieve a hash
client.hgetall('user')
  .then(res => console.log(res)) // { name: 'Alice', age: '25' }
  .catch(err => console.log(err));
``` 

## Closing the Connection 

To close the connection to Redis, you can use the `disconnect` method of the node-redis module. This will gracefully close the connection and resolve any pending commands. For example: 

```javascript
// Disconnect from Redis
client.disconnect()
  .then(() => console.log('Disconnected from Redis'))
  .catch(err => console.log('Failed to disconnect from Redis', err));
``` 

## Conclusion 

In this post, I showed you how to use Redis with Node.js using the node-redis module. You learned how to connect to a Redis database, how to work with different Redis data structures, and how to close the connection. I hope you found this post useful and informative. If you have any questions or feedback, please leave a comment below. Thank you for reading!