{"id":"a3b0a6477bfba49a","repo":"nestjs/nest","slug":"corrupted-length-value-rawcontentlength-suppl","errorCode":null,"errorMessage":"Corrupted length value \"${rawContentLength}\" supplied in a packet","messagePattern":"Corrupted length value \"(.+?)\" supplied in a packet","errorType":"exception","errorClass":"CorruptedPacketLengthException","httpStatus":null,"severity":"error","filePath":"packages/microservices/helpers/json-socket.ts","lineNumber":60,"sourceCode":"        throw new MaxPacketLengthExceededException(bufferLength);\n      }\n\n      if (this.contentLength === null) {\n        const i = this.buffer.indexOf(this.delimiter);\n        /**\n         * Check if the buffer has the delimiter (#),\n         * if not, the end of the buffer string might be in the middle of a content length string\n         */\n        if (i === -1) {\n          break;\n        }\n        const rawContentLength = this.buffer.substring(0, i);\n        this.contentLength = parseInt(rawContentLength, 10);\n\n        if (isNaN(this.contentLength)) {\n          this.contentLength = null;\n          this.buffer = '';\n          throw new CorruptedPacketLengthException(rawContentLength);\n        }\n        this.buffer = this.buffer.substring(i + 1);\n      }\n\n      if (this.contentLength !== null) {\n        const length = this.buffer.length;\n        if (length === this.contentLength) {\n          this.handleMessage(this.buffer);\n          // handleMessage resets contentLength and buffer; next iteration will break\n        } else if (length > this.contentLength) {\n          const message = this.buffer.substring(0, this.contentLength);\n          const rest = this.buffer.substring(this.contentLength);\n          this.handleMessage(message); // resets this.buffer to ''\n          this.buffer = rest; // restore remaining data for next iteration\n          continue;\n        } else {\n          // Incomplete message — wait for more data\n          break;","sourceCodeStart":42,"sourceCodeEnd":78,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/packages/microservices/helpers/json-socket.ts#L42-L78","documentation":"Thrown as CorruptedPacketLengthException from JsonSocket.handleData() when the bytes before the '#' delimiter cannot be parsed by parseInt() as an integer (parseInt yields NaN). The NestJS TCP framing protocol is '<length>#<json-body>'; if the length prefix is non-numeric (e.g. garbage, a partial previous frame, or a non-NestJS client speaking a different protocol), the socket cannot determine the message boundary and rejects the frame, tearing the connection down via TcpSocket.onData().","triggerScenarios":"A non-NestJS client/server connects to the TCP microservice port and sends raw bytes not framed as '<int>#<json>'. A previous oversized/corrupt frame left residue in the buffer that gets parsed as a length prefix. A man-in-the-middle or proxy that mangles the framing. Mismatched serializer that writes data without the '#'-delimited length header.","commonSituations":"Pointing a plain TCP/HTTP client at a NestJS TCP microservice port. A load balancer or proxy rewriting the byte stream. Connecting a NestJS TCP client to a non-NestJS TCP server that uses a different framing. Leftover bytes after a MaxPacketLength reset on a connection that wasn't fully closed.","solutions":["Ensure both endpoints speak the NestJS TCP framing protocol ('<length>#<json>') — use NestJS ClientTCP against a NestJS ServerTCP.","Make sure no proxy/LB rewrites the byte stream; use raw L4 pass-through for the TCP transport.","Confirm the serializer on the sender produces the standard framed format and the deserializer on the receiver matches.","Drop and reconnect: a corrupted frame is unrecoverable on that socket; the connection is closed by design."],"exampleFix":"// before\n// plain net.Socket client writing raw JSON to a NestJS TCP server -> CorruptedPacketLengthException\nconst sock = net.connect(3001, '127.0.0.1');\nsock.write(JSON.stringify({ pattern: 'x', data: 1 }));\n\n// after\nconst client = new ClientTCP({ host: '127.0.0.1', port: 3001 });\nawait client.connect();\nclient.send('x', 1).subscribe();","handlingStrategy":"validation","validationCode":"// Validate that the peer speaks the NestJS TCP framing protocol before bulk traffic.\n// (No public pre-flight; instead only connect NestJS ClientTCP to NestJS ServerTCP.)\nfunction assertNestTcpPeer(server: { transport?: string }) {\n  if (server.transport && server.transport !== 'TCP') {\n    throw new Error('Expected a NestJS TCP server for framed communication.');\n  }\n}","typeGuard":"const isCorruptedPacketLength = (e: unknown): boolean =>\n  /Corrupted length value/.test((e as Error)?.message ?? '');","tryCatchPattern":"// Connection is torn down on this error; catch at the call site and reconnect with a known-good peer.\ntry {\n  await firstValueFrom(client.send('x', 1));\n} catch (e) {\n  if (isCorruptedPacketLength(e)) { /* peer is not NestJS TCP; switch client/fix framing */ }\n  else throw e;\n}","preventionTips":["Only connect NestJS ClientTCP to a NestJS ServerTCP endpoint.","Avoid L7 proxies that rewrite the byte stream; use L4 pass-through.","Keep serializer/deserializer matched on both ends so framing stays '<int>#<json>'."],"tags":["tcp","framing","protocol","json-socket","typescript"],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}