{"id":"7cefa0cca4952e42","repo":"nestjs/nest","slug":"not-initialized-please-call-the-connect-method-7cefa0","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-tcp.ts","lineNumber":182,"sourceCode":"      }\n      this.routingMap.clear();\n    }\n  }\n\n  public on<\n    EventKey extends keyof TcpEvents = keyof TcpEvents,\n    EventCallback extends TcpEvents[EventKey] = TcpEvents[EventKey],\n  >(event: EventKey, callback: EventCallback) {\n    if (this.socket) {\n      this.socket.on(event, callback as any);\n    } else {\n      this.pendingEventListeners.push({ event, callback });\n    }\n  }\n\n  public unwrap<T>(): T {\n    if (!this.socket) {\n      throw new Error(\n        'Not initialized. Please call the \"connect\" method first.',\n      );\n    }\n    return this.socket.netSocket as T;\n  }\n\n  protected publish(\n    partialPacket: ReadPacket,\n    callback: (packet: WritePacket) => any,\n  ): () => void {\n    try {\n      const packet = this.assignPacketId(partialPacket);\n      const serializedPacket = this.serializer.serialize(packet);\n\n      this.routingMap.set(packet.id, callback);\n      this.socket!.sendMessage(serializedPacket);\n\n      return () => this.routingMap.delete(packet.id);","sourceCodeStart":164,"sourceCodeEnd":200,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/packages/microservices/client/client-tcp.ts#L164-L200","documentation":"Thrown by ClientTCP.unwrap() when this.socket is null. this.socket is the JsonSocket wrapper around the raw net.Socket, created by connect(). unwrap() returns the underlying netSocket (the raw TCP socket) so you can apply native socket options; before connect() there is no socket.","triggerScenarios":"Calling client.unwrap() before client.connect() resolves. Calling unwrap() after handleClose() which nulls this.socket and connectionPromise. Network drop followed by an unwrap() before reconnect completes.","commonSituations":"Setting socket options (setKeepAlive, setTimeout, setNoDelay) in onModuleInit before awaiting connect(). Reconnect/error handler logic that calls unwrap() on a client whose socket was just closed. TCP server not yet listening at startup so connect() fails and downstream unwrap() throws.","solutions":["Await client.connect() before client.unwrap().","In reconnect handlers, re-await connect() before unwrap(); do not unwrap() right after handleClose.","Ensure the TCP microservice server host/port is reachable so connect() completes.","Gate unwrap() on the status Observable (TcpStatus.CONNECTED)."],"exampleFix":"// before\nconst client = new ClientTCP({ host: '127.0.0.1', port: 3001 });\nconst sock = client.unwrap(); // throws\n\n// after\nawait client.connect();\nconst sock = client.unwrap<Socket>();\nsock.setKeepAlive(true, 1000);","handlingStrategy":"validation","validationCode":"async function getSocket(client: ClientTCP) {\n  await client.connect();\n  return client.unwrap();\n}","typeGuard":"import { ClientTCP } from '@nestjs/microservices';\nconst isTcpClient = (c: unknown): c is ClientTCP => c instanceof ClientTCP;\nfunction isReady(c: ClientTCP): boolean { return !!(c as any).socket; }","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() before unwrap(); verify host/port is reachable.","In reconnect handlers, re-await connect() before unwrap().","Recreate the client after close()."],"tags":["tcp","client-proxy","lifecycle","typescript"],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}