{"id":"f6e8339073d8d5cf","repo":"nestjs/nest","slug":"not-initialized-please-call-the-connect-method-f6e833","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-nats.ts","lineNumber":159,"sourceCode":"        default:\n          this.logger.log(\n            `NatsStatus: type: \"${status.type}\", data: \"${data}\".`,\n          );\n          break;\n      }\n    }\n  }\n\n  public on<\n    EventKey extends keyof NatsEvents = keyof NatsEvents,\n    EventCallback extends NatsEvents[EventKey] = NatsEvents[EventKey],\n  >(event: EventKey, callback: EventCallback) {\n    this.statusEventEmitter.on(event as string | symbol, callback as any);\n  }\n\n  public unwrap<T>(): T {\n    if (!this.natsClient) {\n      throw new Error(\n        'Not initialized. Please call the \"connect\" method first.',\n      );\n    }\n    return this.natsClient as T;\n  }\n\n  public createSubscriptionHandler(\n    packet: ReadPacket & PacketId,\n    callback: (packet: WritePacket) => any,\n  ) {\n    return async (error: string | Error | undefined, natsMsg: NatsMsg) => {\n      if (error) {\n        return callback({\n          err: error,\n        });\n      }\n      const rawPacket = natsMsg.data;\n      if (rawPacket?.length === 0) {","sourceCodeStart":141,"sourceCodeEnd":177,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/packages/microservices/client/client-nats.ts#L141-L177","documentation":"Thrown by ClientNats.unwrap() when this.natsClient is null — the NATS connection has not been established. unwrap() returns the raw nats.Client for native subscription/JetStream access; connect() is what creates and stores natsClient. Calling unwrap() beforehand is an error because there is no underlying connection to expose.","triggerScenarios":"Calling client.unwrap() before client.connect() resolves. Using unwrap() in a constructor or OnModuleInit that runs before the async connect() finishes. Reusing a client after close() has cleared the reference.","commonSituations":"Calling native NATS APIs (nats.subscribe, JetStream management) too early in the NestJS lifecycle. Manual lifecycle management where connect() is invoked conditionally or after a delay. Race between application bootstrap and a request that needs the raw client.","solutions":["Await client.connect() before client.unwrap().","Drive connect() from OnModuleInit (await it) so unwrap() in later handlers is safe.","After close(), construct a fresh ClientNats rather than unwrap()-ing the torn-down instance.","Gate unwrap() on the status Observable emitting NatsStatus.CONNECTED."],"exampleFix":"// before\nconst client = new ClientNats({ options: {...} });\nconst nats = client.unwrap(); // throws\n\n// after\nawait client.connect();\nconst nats = client.unwrap<Client>();","handlingStrategy":"validation","validationCode":"async function getNats(client: ClientNats) {\n  await client.connect();\n  return client.unwrap();\n}","typeGuard":"import { ClientNats } from '@nestjs/microservices';\nconst isNatsClient = (c: unknown): c is ClientNats => c instanceof ClientNats;\nfunction isReady(c: ClientNats): boolean { return !!(c as any).natsClient; }","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 unwrap().","Gate unwrap() on status emitting CONNECTED.","Recreate the client after close()."],"tags":["nats","client-proxy","lifecycle","typescript"],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}