[NestJS] node-redis TLS Support Sample Code

Tadashi Shigeoka ·  Tue, April 6, 2021

I’ll introduce sample code for TLS support with node-redis in NestJS.

NestJS

Background: How to Support TLS with node-redis?

This time I researched how to support TLS using node-redis and wrote sample code.

Background Knowledge: Redis TLS Support

SSL/TLS support in Redis started from version 6 as an optional feature.

TLS Support

SSL/TLS is supported by Redis starting with version 6 as an optional feature that needs to be enabled at compile time.

Quote from: TLS Support – Redis

node-redis TLS Options

Property: tls

Default: null

Description: An object containing options to pass to tls.connect to set up a TLS connection to Redis (if, for example, it is set up to be accessible via a tunnel).

Quote from: redis.createClient() - NodeRedis/node-redis at v3.1.0

Preparation: Issuing SSL/TLS Server Certificates for Local Environment

I issued the local environment SSL/TLS server certificates like localhost-key.pem and localhost.pem using mkcert.

Sample Code: Specifying tls Options in redis.createClient()

Here’s sample code for specifying tls options in redis.createClient() with NestJS:

import { createClient, RedisClient } from 'redis';

let redisClinet;
if (process.env.REDIS_TLS_URL) {
  redisClinet = createClient(process.env.REDIS_TLS_URL, {
    tls: {
      requestCert: true,
      rejectUnauthorized: false,
      cert: fs.readFileSync('/your_path/localhost.pem', 'utf8'),
      key: fs.readFileSync('/your_path/localhost-key.pem', 'utf8'),
    },
  });
} else {
  redisClinet = createClient({
    host: process.env.REDIS_HOST,
    port: parseInt(process.env.REDIS_PORT || '')
  });
}

That’s all from the Gemba.