# How to use Redis from Node.js

> Learn how to use Redis from Node.js with the node-redis client: connect, store and read keys, and work with lists, sets, hashes, and pub/sub subscriptions.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2022-01-24 | Topics: [Redis](https://flaviocopes.com/tags/redis/) | Canonical: https://flaviocopes.com/how-to-use-redis-nodejs/

One of the most popular libraries to work with a Redis server from a [Node.js](https://flaviocopes.com/nodejs/) app is `node-redis`, available at <https://github.com/NodeRedis/node-redis>.

Install the library in your project:

```sh
npm install redis
```

> Tip: don't forget to first run `npm init -y` if the project is brand new and you don't have a `package.json` file already.

## Connect to the Redis instance

Once the library is installed, require it in your project using

```js
const redis = require('redis')
```

or

```js
import redis from 'redis'
```

Once you have the `redis` object, create a new client using

```js
const client = redis.createClient({
  url: 'redis://YOUR REDIS INSTANCE URL'
})
```

and connect using (inside an async function):

```js
await client.connect()
```

Once you have the client, we can perform all the things we know that Redis can do.

To close the connection, call:

```js
client.quit()
```

## Store and retrieve key values

Store a key value pair into redis using `set()`:

```js
client.set("<key>", "<value>")
```

Example:

```js
client.set("name", "Flavio")
client.set("age", 37)
```

If you run `KEYS *` in `redis-cli` on a clean Redis server, you'll see the two keys appearing:

![Redis CLI terminal showing KEYS * command output listing name and age keys](https://flaviocopes.com/images/how-to-use-redis-nodejs/keys.png)

You can get the value stored in a key using `get()`:

```js
const value = await client.get("name")
```

Delete a key/value string using

```js
client.del("names")
```

## Working with lists

In Redis we can work with lists using the 

- `LPUSH`
- `RPUSH`
- `LTRIM`
- `LRANGE` 

commands we introduced in the Redis module. They map directly as `client` object methods.

Create a list using

```js
client.lPush('names', 'Flavio')
```

Push a new item to the bottom of the list: 

```js
client.rPush('names', 'Roger')
```

Or at the top of the list:

```js
client.lPush('names', 'Syd')
```

List all the items in a list using:

```js
const result = await client.lRange('names', 0, -1)
//result is [ 'Roger', 'Flavio', 'Syd' ]
```

Drop items from a list using

```js
client.rPop('names')
```

Delete a list using

```js
client.del('names')
```

## Working with sets

In Redis we work with sets using

- `SADD`
- `SPOP`
- `SMEMBERS`.

and other Redis commands, that map directly as `client` object methods.

Create a set using

```js
client.sAdd('names', 'Flavio')
```

Add more items to the set:

```js
client.sAdd('names', 'Roger')
```

You can add multiple ones at once:

```js
client.sAdd('names', 'Roger', 'Syd')
```

also by passing an array:

```js
const names = ['Flavio', 'Roger', 'Syd']
client.sAdd('names', names)
```

List all the items in a set using:

```js
const names = await client.sMembers('names')
```

Drop a random item from a set using:

```js
client.sPop('names')
```

Add a second parameter to drop multiple random items:

```js
client.sPop('names', 3)
```

Delete a set using

```js
client.del('names')
```

## Working with hashes

In Redis we work with hashes using a set of commands that include

- `HMSET`
- `HGETALL`
- `HSET`
- `HINCRBY`.

and other commands we introduced in the Redis module, that map directly as `client` object methods.

Create a hash using

```js
client.hSet('person:1', 'name', 'Flavio', 'age', 37)
```

To get all the properties of a user, use HGETALL:

```js
const items = client.hGetAll('person:1')
```

You can update a hash property using HSET:

```js
client.hSet('person:1', 'age', 38)
```

You can increment a value stored in a hash using HINCRBY:

```js
client.hIncrBy('person:1', 'age', 1)
```

Delete a hash using

```js
client.del('person:1')
```

## Subscriptions

Subscriptions are an amazing feature of Redis, powering us to do really fancy things in Node.js.

A publisher sends a message on a channel. Multiple subscribers receive it.

Subscribe to a channel using

```js
await subscriber.subscribe('dogs', (message) => {
  console.log(message);
})
```

Publish to a channel using `client.publish('<channel>', '<message>')`

```js
client.publish('dogs', 'Roger')
```

Be aware that you can't publish and subscribe from the same `client` instance.

To do so in the same app, create 2 clients:

```js
const subscriber = redis.createClient({ ... })
const publisher = redis.createClient({ ... })

await subscriber.subscribe('dogs', (message) => {
  console.log(channel, message);
})

publisher.publish('dogs', 'Roger')
```
