Skip to content

fix(response): set status and Content-Length for JSON null body - #2022

Open
NgoQuocViet2001 wants to merge 1 commit into
koajs:masterfrom
NgoQuocViet2001:fix-json-null-status
Open

NgoQuocViet2001 wants to merge 1 commit into
koajs:masterfrom
NgoQuocViet2001:fix-json-null-status

Conversation

@NgoQuocViet2001

@NgoQuocViet2001 NgoQuocViet2001 commented Oct 24, 2026 •

Copy link
Copy Markdown

Checklist

  • I have ensured my pull request is not behind the main or master branch of the original repository.
  • I have rebased all commits where necessary so that reviewing this pull request can be done without having to merge it first.
  • I have written a commit message that passes commitlint linting.
  • I have ensured that my code changes pass linting tests.
  • I have ensured that my code changes pass unit tests.
  • I have described my pull request and the reasons for code changes along with context if necessary.

When the response type is JSON and the body is set to null or undefined, Koa sends null, but that branch of set body returns before the usual status and length handling. ctx.type = 'json'; ctx.body = null responds 404 Not Found with body null. ctx.body = 'hello world'; ctx.type = 'json'; ctx.body = null keeps Content-Length: 11 while writing 4 bytes, so the client waits for bytes that never come.

The branch now does what the string branch does: it sets the status to 200 unless one was set explicitly, and sets Content-Length to the length of null. An explicit status such as ctx.status = 404 is kept. Apps that set the JSON type first and then assign a null result will get 200 instead of 404. #2014 changes the same lines (stream cleanup only), so whichever lands second needs a small rebase.

  • Ran: npm run lint, npm run build && npm test (470 passing), npm run test:coverage.
  • Checked: 3 of the 4 new tests fail on master (expected 200 "OK", got 404 "Not Found", aborted, 11 !== 4). All 4 pass with this change.

Summary by Sourcery

Correct response handling for JSON null bodies so status and Content-Length remain consistent with the returned payload.

Bug Fixes:

  • Ensure JSON null responses default to HTTP 200 and report the correct Content-Length while preserving explicitly assigned statuses.

Tests:

  • Add coverage for JSON null response status, headers, body length, explicit statuses, and replacement of stale Content-Length values.

Summary by CodeRabbit

  • Bug Fixes
    • Responses with a JSON content type and a null body now return the valid JSON value null, with the correct content length.
    • These responses use status 200 when no status was specified, preserve an explicitly selected status, and replace any previous content length with the correct value.

@coderabbitai

coderabbitai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9c0cbef6-3529-42a0-92f9-c4478ba5ae64
Commits

Reviewing files that changed from the base of the PR and between a82feec and 31cac38.

Files selected for processing: 3
  • __tests__/application/respond.test.js
  • __tests__/response/length.test.js
  • lib/response.js

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Walkthrough

When the response type is JSON and the body is null, the response setter serializes the body as 'null' and sets its content length. It preserves an explicitly selected status. Added tests check the default status and headers, retention of a 404 status, and the content length.

Suggested reviewers: yowainwright

Priority: Normal

Merge Risk: Minimal · up to 31cac

The reviewed behavior is ready to merge after normal checks; no actionable risk was identified.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title "fix(response): set status and Content-Length for JSON null body" matches the main change. The raw summary says lib/response.js now sets status to 200 when no explicit status exists, and set…
Docstring Coverage Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 3…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "fix(response): set status and Content-Length for JSON null body" matches the main change. The raw summary says lib/response.js now sets status to 200 when no explicit status exists, and sets Content-Length from the serialized null body. The added tests cover that behavior. The title is specific and follows a conventional commit style. The objectives describe the same goal.

Full details: Docstring Coverage

Explanation

No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check. Docstring coverage is scoped to functions touched by this diff. Analyzed 0 functions across 3 files.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@sourcery-ai

sourcery-ai Bot commented Oct 24, 2026

Copy link
Copy Markdown

Reviewer's Guide

Fix JSON responses whose body is null or undefined by treating the serialized null body like the normal response path: defaulting to 200, preserving explicit statuses, and setting Content-Length to 4; accompanying tests cover status and stale-length regressions.

Sequence diagram for JSON null response handling

sequenceDiagram
    participant App
    participant Context
    participant Response

    App->>Context: set type to application/json
    App->>Context: set body to null
    Context->>Response: set _body to null
    alt status not explicitly set
        Context->>Response: set status to 200
    else status explicitly set
        Context->>Response: preserve explicit status
    end
    Context->>Response: set length to Buffer.byteLength(_body)
    Response-->>App: send JSON null with Content-Length 4
Loading

File-Level Changes

Change Details Files
Ensure JSON null bodies receive normal success-status and length handling.
  • Set status to 200 unless an explicit status was provided.
  • Serialize null as a four-byte body and update Content-Length, replacing stale values.
lib/response.js
Add regression coverage for JSON null response behavior.
  • Verify default status, JSON content type, body, and length.
  • Verify explicit statuses are preserved.
  • Verify prior Content-Length values are replaced.
__tests__/application/respond.test.js
__tests__/response/length.test.js

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.90%. Comparing base (a82feec) to head (31cac38).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #2022   +/-   ##
=======================================
  Coverage   99.90%   99.90%           
=======================================
  Files           9        9           
  Lines        2144     2146    +2     
=======================================
+ Hits         2142     2144    +2     
  Misses          2        2           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've reviewed your changes and they look great!

Sourcery assessment

Approved.


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant