Skip to main content

Command Palette

Search for a command to run...

[Redis] How to Use Redis in Node.js

Updated
[Redis] How to Use Redis in Node.js

Redis

What is Redis?

Redis is a cache system and in-memory database that stores data in a key-value format. Since in-memory databases store all data in memory, they are much faster than retrieving data from a traditional DBMS. Redis utilizes a data structure called Sorted-Set to sort data more quickly and easily.


I wanted to use Redis to store refresh tokens. I tried to use the elastic cache provided by AWS, but it charged me. I also tried to download redis-server directly to EC2 and connect it, but it didn't work. Finally, I found a solution in Redislabs, which provides a free Redis DB with a size limit of 30MB.

How to Connect Redis with Node.js Project

  1. Click Try Free and sign up in Redislabs

  2. Select AWS and Region: US East (N.Virginia) us-east-1

  3. You can now see the free DB is created.

  4. Under Name, we can see important information we are going to use in the project.

  • host, post: we can copy host and port info. For host, we should omit the port number at the end of the endpoint (e.g. :19231)

  • password: we can copy randomly generated password by scrolling down a bit

  1. On Terminal, run the following commands:
  • Windows
> npm install -g redis-cli # install redis cli

> rdcli -h <host> -p <port> -a <password> # connect to redis cloud
  • Linux
$ apt-get install redis-tools # install redis cli

$ redis-cli -v # check version

$ redis-cli -h <endpoint> -p <port> -a <password> # oonnect to redis cloud
  1. Add the environment variables
  • npm install dotenv: install the environment variables module

  • .env file will be automatically created under the root directory

  • Enter the following info:

# .env file
REDIS_HOST=redis-10943.c114.us-east-14.ec2.cloud.redislabs.com
REDIS_PORT=10943
REDIS_USERNAME=default
REDIS_PASSWORD=abcdefghijklmnopqrstuvwsyz
  1. Install redis module
  • npm install redis
  1. Connect redis to the local
  • import redis and dotenv modules
const redis = require("redis");
require("dotenv").config();

const redisClient = redis.createClient({ 
  url: `redis://${process.env.REDIS_USERNAME}:${process.env.REDIS_PASSWORD}@${process.env.REDIS_HOST}:${process.env.REDIS_PORT}/0`,
  legacyMode: true
}); // set the legacy mode (v4 updated version is based on the Promise, but if you want to use v3 version based on the callback, you must set legacy mode_
redisClient.on('connect', () => {
   console.info('Redis connected!');
});
redisClient.on('error', (err) => {
   console.error('Redis Client Error', err);
});
redisClient.connect().then(); // connect to redis v4 (async)
const redisCli = redisClient.v4;
  1. Use Redis in JavaScript

    1. Save data: let bool = await redisClient.v4.set('key', '123');

    2. Bring data: let data = redisClient.v4.get('key');

      IMPORTANT: TypeError: A key should not be a Number type

    3. Delete data: const n = await redisCli.exists('username'); -> check if exists
      if(n) await redisCli.del('username'); -> delete

    4. Modify data: redisCli.rename('key', 'changed'); -> if key exists, change value to 'changed'

  2. Defind Redis Class

class RedisClientRepository {
    constructor() {
        this.redisClient = redis.createClient({
            url: `redis://${process.env.REDIS_USERNAME}:${process.env.REDIS_PASSWORD}@${process.env.REDIS_HOST}:${process.env.REDIS_PORT}/0`,
            legacyMode: true,
        });

        this.redisConnected = false;
    }

    initialize = async () => {
        this.redisClient.on("connect", () => {
            this.redisConnected = true;
            console.info("Redis connected!");
        });
        this.redisClient.on("error", (err) => {
            console.error("Redis Client Error", err);
        });
        if (!this.redisConnected) this.redisClient.connect().then(); // redis v4 connection (async)
    };

    setRefreshToken = async (refreshToken, userId) => {
        await this.initialize();
        await this.redisClient.v4.set(refreshToken, userId);
    };

    getRefreshToken = async (refreshToken) => {
        await this.initialize();
        const token = await this.redisClient.v4.get(refreshToken);
        return token;
    };

    deleteRefreshToken = async (refreshToken) => {
        await this.initialize();
        await this.redisClient.v4.del(refreshToken);
    };
}