nestjs/nest · error · Error

Not initialized. Please call the "connect" method first.

Error message

Not initialized. Please call the "connect" method first.

What it means

Thrown by ClientRedis.unwrap() when either this.pubClient or this.subClient is null. Redis uses two connections (publisher + subscriber); unwrap() returns [pubClient, subClient] as a tuple. Until connect() creates both, there is nothing to return, so the call is rejected with the generic 'Not initialized' message.

Source

Thrown at packages/microservices/client/client-redis.ts:220

      retryStrategy,
    };
  }

  public on<
    EventKey extends keyof RedisEvents = keyof RedisEvents,
    EventCallback extends RedisEvents[EventKey] = RedisEvents[EventKey],
  >(event: EventKey, callback: EventCallback) {
    if (this.subClient && this.pubClient) {
      this.subClient.on(event, (...args: [any]) => callback('sub', ...args));
      this.pubClient.on(event, (...args: [any]) => callback('pub', ...args));
    } else {
      this.pendingEventListeners.push({ event, callback });
    }
  }

  public unwrap<T>(): T {
    if (!this.pubClient || !this.subClient) {
      throw new Error(
        'Not initialized. Please call the "connect" method first.',
      );
    }
    return [this.pubClient, this.subClient] as T;
  }

  public createRetryStrategy(times: number): undefined | number {
    if (this.isManuallyClosed) {
      return undefined;
    }
    if (!this.getOptionsProp(this.options, 'retryAttempts')) {
      this.logger.error(
        'Redis connection closed and retry attempts not specified',
      );
      return;
    }
    if (times > this.getOptionsProp(this.options, 'retryAttempts', 0)) {
      this.logger.error('Retry time exhausted');

View on GitHub (pinned to 6ec0e2783d)

Solutions

  1. Await client.connect() before client.unwrap().
  2. Verify both Redis connections succeed — check broker auth and network for both pub and sub sockets.
  3. After close(), build a new ClientRedis rather than unwrap()-ing the closed instance.
  4. Subscribe to client.status and only unwrap() after CONNECTED.

Example fix

// before
const client = new ClientRedis({ options: {...} });
const [pub, sub] = client.unwrap(); // throws

// after
await client.connect();
const [pub, sub] = client.unwrap<[RedisClient, RedisClient]>();
Defensive patterns

Strategy: validation

Validate before calling

async function getClients(client: ClientRedis) {
  await client.connect();
  return client.unwrap();
}

Type guard

import { ClientRedis } from '@nestjs/microservices';
const isRedisClient = (c: unknown): c is ClientRedis => c instanceof ClientRedis;
function isReady(c: ClientRedis): boolean {
  return !!(c as any).pubClient && !!(c as any).subClient;
}

Try / catch

try {
  return client.unwrap();
} catch (e) {
  if (/Not initialized/.test(e?.message)) { await client.connect(); return client.unwrap(); }
  throw e;
}

Prevention

When it happens

Trigger: Calling client.unwrap() before client.connect() resolves (both pub and sub clients must be open). Calling unwrap() after close() which destroys both clients. Asymmetric failure where the sub client connected but the pub client did not (or vice versa) — the OR check fails on the missing one.

Common situations: onModuleInit lifecycle ordering where unwrap() runs before the Redis connection promise resolves. Reconnect logic that calls close()+unwrap(). Redis broker refusing one of the two connections (auth/firewall) leaving the tuple incomplete.

Related errors


AI-assisted analysis of nestjs/nest@6ec0e2783d (2026-08-03). Data as JSON: /data/errors/002eadb2c7fe9b74.json. Report an issue: GitHub.