Skip to content

fix(response): keep the Blob content type instead of forcing octet-stream#1987

Open
spokodev wants to merge 1 commit into
koajs:masterfrom
spokodev:fix/response-blob-content-type
Open

fix(response): keep the Blob content type instead of forcing octet-stream#1987
spokodev wants to merge 1 commit into
koajs:masterfrom
spokodev:fix/response-blob-content-type

Conversation

@spokodev

@spokodev spokodev commented Jul 1, 2026

Copy link
Copy Markdown

When a Blob is assigned to ctx.body, Koa forces Content-Type: application/octet-stream and ignores the Blob's own type. A Blob carries its MIME type in blob.type, so a typed Blob such as new Blob(data, { type: 'image/png' }) (or a Blob returned by fetch(...).then(r => r.blob())) is sent with the wrong content type. Browsers then download the payload instead of rendering it, and any client that negotiates on Content-Type sees the wrong value.

The sibling Response body path already copies the body's own Content-Type, and the original feature request (#1777) specified ctx.type = blob.type, so the Blob path is the outlier.

Cause

In lib/response.js, the Blob branch of the body setter is:

if (setType) this.type = 'bin'

'bin' maps through mime-types to application/octet-stream, discarding val.type. The setType guard (an explicitly preset Content-Type wins) is correct; only the fallback value is wrong.

Fix

if (setType) this.type = val.type || 'bin'

Honor the Blob's own MIME type when present, and fall back to application/octet-stream for an untyped Blob (the existing default). An explicit ctx.type still wins.

Added two tests to __tests__/response/body.test.js: a typed Blob keeps its type, and an explicit content type is not overridden. The first fails before this change; the full suite (442) stays green.

Summary by Sourcery

Preserve Blob MIME types when assigning them to the response body while keeping existing fallbacks and content-type precedence.

Bug Fixes:

  • Ensure a Blob assigned to the response body uses its own MIME type when present instead of always defaulting to application/octet-stream.
  • Respect an explicitly set response content type when assigning a Blob body so it is not overridden.

Tests:

  • Add tests verifying that typed Blobs preserve their content type on the response and that explicit content types are not overridden by Blob bodies.

Summary by CodeRabbit

  • Bug Fixes
    • Blob responses now preserve an existing media type when one is provided, instead of always defaulting to a generic type.
    • Explicit response content types are now respected when setting a Blob body, preventing them from being overwritten.
  • Tests
    • Added coverage for Blob content-type handling to verify both default behavior and explicit type precedence.

…ream

Assigning a Blob to ctx.body forced Content-Type: application/octet-stream
and ignored the Blob's own type. A typed Blob such as
new Blob(data, { type: 'image/png' }) was sent with the wrong content type,
so browsers download the payload instead of rendering it. The Response body
path already copies the body's own Content-Type, and the original feature
request (koajs#1777) specified ctx.type = blob.type.

Use val.type when present and fall back to application/octet-stream for an
untyped Blob. An explicitly preset Content-Type still wins.
@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2a23c56c-7c6b-4fd9-8727-f6a7d29b2f6f

📥 Commits

Reviewing files that changed from the base of the PR and between 52d5e8f and d69a024.

📒 Files selected for processing (2)
  • __tests__/response/body.test.js
  • lib/response.js

📝 Walkthrough

Walkthrough

The body setter in lib/response.js was modified so that, when setting a Blob as the response body and Content-Type has not yet been set, the response content-type is derived from the Blob's type property, falling back to 'bin' if not present. Previously, 'bin' was always used. Test coverage was added to verify this behavior, including a case confirming an explicitly set res.type is not overridden by a Blob's differing type.

Compact metadata:

  • Files changed: 2
  • Lines changed: +14/-1
  • Estimated review effort: Medium

Related issues: None specified

Related PRs: None specified

Suggested labels: bug, tests

Suggested reviewers: None specified

Poem:
A rabbit sniffs a Blob one day,
"What type are you?" it starts to say.
"image/png," the Blob replies,
So content-type no longer lies.
Tests confirm it, snug and tight—
Hop along, the code's just right! 🐰

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: preserving a Blob's content type instead of forcing octet-stream.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.

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 Jul 1, 2026

Copy link
Copy Markdown
Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adjusts Koa’s response body handling so that when a Blob is assigned to ctx.body, its own MIME type is preserved (if present) instead of always defaulting to application/octet-stream, and adds tests to lock in this behavior and ensure explicit content types remain authoritative.

File-Level Changes

Change Details Files
Preserve a Blob body’s own MIME type when setting the HTTP Content-Type header, while keeping explicit ctx.type precedence and the existing fallback for untyped Blobs.
  • Update the Blob branch of the response body setter to derive the Content-Type from the Blob’s type if available, otherwise fall back to the existing binary default.
  • Retain the existing behavior where a pre-set response type (ctx.type) prevents automatic type inference from the body.
  • Ensure response length is still derived from Blob.size and previous body streams are cleaned up as before.
lib/response.js
Add regression tests covering Blob content type preservation and explicit content type precedence.
  • Add a test asserting that assigning a typed Blob to res.body sets the Content-Type header to the Blob’s type value.
  • Add a test asserting that when res.type is explicitly set, assigning a typed Blob to res.body does not overwrite the existing Content-Type header (including charset).
__tests__/response/body.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

@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 is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@codecov

codecov Bot commented Jul 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.90%. Comparing base (52d5e8f) to head (d69a024).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #1987   +/-   ##
=======================================
  Coverage   99.90%   99.90%           
=======================================
  Files           9        9           
  Lines        2109     2109           
=======================================
  Hits         2107     2107           
  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.

@Ziiyodullayevv Ziiyodullayevv 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.

Good fix for Blob content type handling. Keeping the original content type instead of forcing octet-stream preserves the intended MIME type.

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.

2 participants