{"id":"021cf14ab6a815ff","repo":"nestjs/nest","slug":"could-not-parse-json-err-message-request-data","errorCode":null,"errorMessage":"Could not parse JSON: ${err.message}\nRequest data: ${data}","messagePattern":"Could not parse JSON: (.+?)\nRequest data: (.+?)","errorType":"exception","errorClass":"InvalidJSONFormatException","httpStatus":null,"severity":"error","filePath":"packages/microservices/helpers/tcp-socket.ts","lineNumber":70,"sourceCode":"  ): any;\n\n  private onData(data: Buffer) {\n    try {\n      this.handleData(data);\n    } catch (e) {\n      this.socket.emit(TcpEventsMap.ERROR, e.message);\n      this.socket.end();\n    }\n  }\n\n  protected abstract handleData(data: Buffer | string): any;\n\n  protected emitMessage(data: string) {\n    let message: Record<string, unknown>;\n    try {\n      message = JSON.parse(data);\n    } catch (e) {\n      throw new InvalidJSONFormatException(e, data);\n    }\n    message = message || {};\n    this.socket.emit('message', message);\n  }\n}\n","sourceCodeStart":52,"sourceCodeEnd":76,"githubUrl":"https://github.com/nestjs/nest/blob/6ec0e2783d15290732447f304d8549b591b9749e/packages/microservices/helpers/tcp-socket.ts#L52-L76","documentation":"Thrown as InvalidJSONFormatException from TcpSocket.emitMessage() when JSON.parse(data) throws on the body of a parsed frame. By the time emitMessage runs, the length-prefixed framing has already succeeded and produced a complete string; this error means that string is not valid JSON. The message includes the underlying parse error and the raw request data for debugging. Like the other framing errors, the socket's 'error' event is emitted and the connection closed by onData().","triggerScenarios":"A well-framed TCP message whose body is not valid JSON (truncated payload, single quotes, trailing commas, comments, or accidental non-JSON text inside a valid length frame). A custom serializer that writes non-JSON (e.g. MessagePack, raw strings) while the receiver uses the default JSON deserializer. Encoding mismatches (UTF-16 vs UTF-8) producing unparseable characters.","commonSituations":"Mismatched serializer on the sender vs deserializer on the receiver (one side JSON, the other not). Hand-crafted frames where the JSON body is malformed. Encoding/locale issues on Windows or with binary blobs. A truncated write that happened to be exactly length-prefixed but contained a partial JSON document.","solutions":["Ensure the sender uses a serializer whose output the receiver's deserializer can parse — default both to JSON, or set both to the same custom serializer/deserializer pair.","Validate payloads are JSON-serializable before sending (no BigInt without a custom serializer, no circular refs, no undefined).","Check for encoding issues — the transport expects UTF-8 strings.","If you need non-JSON, configure options.serializer and options.deserializer consistently on both ClientTCP and ServerTCP."],"exampleFix":"// before\n// sender: custom serializer emits a plain string\nnew ClientTCP({ ... , serializer: new PlainTextSerializer() });\n// receiver: default JSON deserializer -> InvalidJSONFormatException\n\n// after\n// use matching serializer/deserializer on both sides\nnew ClientTCP({ ..., serializer: new MySerializer() });\nnew ServerTCP({ ..., deserializer: new MyDeserializer() });","handlingStrategy":"validation","validationCode":"function assertJsonSerializable(payload: unknown) {\n  try { JSON.stringify(payload); }\n  catch (e) { throw new Error('Payload is not JSON-serializable: ' + e.message); }\n}\nassertJsonSerializable(payload);","typeGuard":"const isInvalidJsonFormat = (e: unknown): boolean =>\n  /Could not parse JSON/.test((e as Error)?.message ?? '');","tryCatchPattern":"try {\n  await firstValueFrom(client.send('x', payload));\n} catch (e) {\n  if (isInvalidJsonFormat(e)) {\n    // align serializer (sender) with deserializer (receiver), or sanitize payload\n  } else throw e;\n}","preventionTips":["Use matching serializer/deserializer on both ends (default JSON, or a shared custom pair).","Strip non-serializable values (undefined, functions, BigInt, circular refs) before send.","Confirm UTF-8 encoding on both sides."],"tags":["tcp","json","serialization","typescript"],"analyzedSha":"6ec0e2783d15290732447f304d8549b591b9749e","analyzedAt":"2026-08-03T17:42:23.673Z","schemaVersion":2}