{"id":"652f5a478b766159","repo":"nestjs/nest","slug":"not-initialized-please-call-the-connect-method-652f5a","errorCode":null,"errorMessage":"Not initialized. Please call the \"connect\" method first.","messagePattern":"Not initialized\\. Please call the \"connect\" method first\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/microservices/client/client-mqtt.ts","lineNumber":189,"sourceCode":"        client.on('message', this.createResponseCallback());\n      }\n    });\n  }\n\n  public on<\n    EventKey extends keyof MqttEvents = keyof MqttEvents,\n    EventCallback extends MqttEvents[EventKey] = MqttEvents[EventKey],\n  >(event: EventKey, callback: EventCallback) {\n    if (this.mqttClient) {\n      this.mqttClient.on(event, callback as any);\n    } else {\n      this.pendingEventListeners.push({ event, callback });\n    }\n  }\n\n  public unwrap<T>(): T {\n    if (!this.mqttClient) {\n      throw new Error(\n        'Not initialized. Please call the \"connect\" method first.',\n      );\n    }\n    return this.mqttClient as T;\n  }\n\n  public createResponseCallback(): (channel: string, buffer: Buffer) => any {\n    return async (channel: string, buffer: Buffer) => {\n      const packet = JSON.parse(buffer.toString());\n      const { err, response, isDisposed, id } =\n        await this.deserializer.deserialize(packet);\n\n      const callback = this.routingMap.get(id);\n      if (!callback) {\n        return undefined;\n      }\n      if (isDisposed || err) {\n        return callback({","sourceCodeStart":171,"sourceCodeEnd":207,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/packages/microservices/client/client-mqtt.ts#L171-L207","documentation":"Thrown by ClientMqtt.unwrap() when this.mqttClient is null, i.e. the underlying mqtt.MqttClient has not been created yet. unwrap() exists to hand back the raw broker client so you can call native MQTT APIs; before connect() runs there is no native client to return, so the call is rejected. connect() creates mqttClient, registers the CONNECT listener, and flips the connectionPromise to resolved.","triggerScenarios":"Calling client.unwrap() before client.connect() (or before the connect() promise resolves). Calling unwrap() after close() has nulled the client. Constructing a ClientMqtt via ClientsModule and immediately calling unwrap() in onModuleInit before awaiting connect().","commonSituations":"DI lifecycle misuse: using unwrap() in OnModuleInit without first awaiting connect() (NestJS does connect lazily, so the first send() triggers it, but unwrap() does not). Calling close() then unwrap() for a reconnect routine. Hot-restart scenarios where the client reference is reused after teardown.","solutions":["Call and await client.connect() before client.unwrap().","If using ClientsModule, await the client.connect() in onModuleInit (or rely on the first emit/send which triggers connect) before unwrap().","After close(), create a new ClientMqtt instance rather than calling unwrap() on the closed one.","Type-narrow before calling: check via the connectionPromise / status Observable."],"exampleFix":"// before\nconst client = new ClientMqtt({ options: {...} });\nconst mqtt = client.unwrap(); // throws\n\n// after\nawait client.connect();\nconst mqtt = client.unwrap<MqttClient>();","handlingStrategy":"validation","validationCode":"// Ensure connect() has run before unwrap()\nasync function getMqtt(client: ClientMqtt) {\n  await client.connect();\n  return client.unwrap();\n}","typeGuard":"import { ClientMqtt } from '@nestjs/microservices';\nimport type { MqttClient } from 'mqtt';\nconst isMqttClient = (c: unknown): c is ClientMqtt => c instanceof ClientMqtt;\nfunction isReady(c: ClientMqtt): boolean { return !!(c as any).mqttClient; }","tryCatchPattern":"try {\n  return client.unwrap();\n} catch (e) {\n  if (/Not initialized/.test(e?.message)) { await client.connect(); return client.unwrap(); }\n  throw e;\n}","preventionTips":["Await connect() in OnModuleInit before any unwrap() call.","Subscribe to client.status and only unwrap() after CONNECTED.","Build a new instance after close(); never unwrap() a closed client."],"tags":["mqtt","client-proxy","lifecycle","typescript"],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}