nestjs/nest · error · Error

No producer initialized. Please, call the "connect" method f

Error message

No producer initialized. Please, call the "connect" method first.

What it means

The `ClientKafka.producer` getter throws when `_producer` is null — i.e. before `connect()` has resolved or after `close()` has been called. All produce-side operations route through this getter, so it is the first thing to fail when the client is used before being connected.

Source

Thrown at packages/microservices/client/client-kafka.ts:86

  protected brokers: string[] | BrokersFunction;
  protected clientId: string;
  protected groupId: string;
  protected producerOnlyMode: boolean;
  protected _consumer: Consumer | null = null;
  protected _producer: Producer | null = null;

  get consumer(): Consumer {
    if (!this._consumer) {
      throw new Error(
        'No consumer initialized. Please, call the "connect" method first.',
      );
    }
    return this._consumer;
  }

  get producer(): Producer {
    if (!this._producer) {
      throw new Error(
        'No producer initialized. Please, call the "connect" method first.',
      );
    }
    return this._producer;
  }

  constructor(protected readonly options: Required<KafkaOptions>['options']) {
    super();

    const clientOptions = this.getOptionsProp(
      this.options,
      'client',
      {} as KafkaConfig,
    );
    const consumerOptions = this.getOptionsProp(
      this.options,
      'consumer',
      {} as ConsumerConfig,

View on GitHub (pinned to 6ec0e2783d)

Solutions

  1. Await `connect()` (or let the framework auto-connect via `@Client`) before producing.
  2. Ensure no `emit`/`send` races the connect promise; chain off `connect().then(...)` if needed.
  3. Call `connect()` again after `close()` before reusing the client.

Example fix

// before
async onModuleInit() {
  this.client.emit('user.created', { id: 1 }); // throws via producer getter
}
// after
async onModuleInit() {
  await this.client.connect();
  this.client.emit('user.created', { id: 1 });
}
Defensive patterns

Strategy: validation

Validate before calling

// Ensure connect() resolved before producing
await this.client.connect();
this.client.emit('user.created', { id: 1 });

Type guard

function hasProducer(c: ClientKafka): boolean { return Reflect.get(c, '_producer') != null; }

Prevention

When it happens

Trigger: Accessing `clientKafka.producer` (directly or via `emit`/`send`) before `connect()` resolves, or after `close()`.

Common situations: Missing `await client.connect()` in `onModuleInit`; race condition where `emit` is called before the connect promise resolves; reusing a client after close without reconnecting.

Related errors


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