Skip to content

Handling leading whitespace in SSE data for Stream Generate Content #963

@hegdeashwin

Description

@hegdeashwin

Thanks for stopping by to let us know something could be better!

PLEASE READ: If you have a support contract with Google, please create an issue in the support console instead of filing on GitHub. This will ensure a timely response.

Is this a client library issue or a product issue? We will only be able to assist with issues that pertain to the behaviors of this library. If the issue you're experiencing is due to the behavior of the product itself, please visit the Support page to reach the most relevant engineers.

If the support paths suggested above still do not result in a resolution, please provide the following details.

Environment details

  • Programming language: JavaScript / TypeScript / Node.js
  • OS: MacOS
  • Language runtime version:
  • Package version: ^1.19.0

Steps to reproduce

Note: I see possibility to occur in enterprise in case we have some custom handling of SSE event and data in between GCP and our service like gateway.

  1. If the stream response includes leading whitespace — for example:
'\n\ndata: {"candidates": [{"content": {"role": "model","parts": [{"text": "Sheldon"}]}}],"usageMetadata": {"trafficType": "ON_DEMAND"},"modelVersion": "gemini-2.0-flash","createTime": "2025-09-14T13:18:29.993482Z","responseId": "pcDGaMrRPIKrnvgP-_WisAs"}\n\n'

— then the condition in this section of the js-genai client evaluates to null, which leads to the error: Incomplete JSON segment at the end.

The regex here:

const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/;
seems to be the problem.

Allowing leading whitespace like following is fixing the stream generate content issue:

const responseLineRE = /^\s*data: (.*)(?:\n\n|\r\r|\r\n\r\n)/;

Making sure to follow these steps will guarantee the quickest resolution possible.

Thanks!

Metadata

Metadata

Assignees

Labels

api: datastreamIssues related to the Datastream API.priority: p2Moderately-important priority. Fix may not be included in next release.type: bugError or flaw in code with unintended results or allowing sub-optimal usage patterns.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions