Skip to content

feat(zod-openapi): optional response validation (strict flags, hooks)#1819

Open
mikan3rd wants to merge 8 commits intohonojs:mainfrom
mikan3rd:add_response_validation
Open

feat(zod-openapi): optional response validation (strict flags, hooks)#1819
mikan3rd wants to merge 8 commits intohonojs:mainfrom
mikan3rd:add_response_validation

Conversation

@mikan3rd
Copy link
Copy Markdown

@mikan3rd mikan3rd commented Mar 25, 2026

Approach

Opt-in response checks aligned with PR #184 (strictStatusCode / strictResponse), with maintainer direction in mind: validate JSON before a Response exists by temporarily wrapping c.json and c.status for the openapi route handler, instead of re-reading the body from a finished response.

Failure handling is configurable via defaultResponseHook and per-route responseHook (third openapi argument may be a request Hook or { hook?, responseHook? }). If neither hook returns a Response, a small JSON 500 body is sent.

Caveats / assumptions

  • Validation applies only to c.json (and c.status when inferring status). c.text / c.html / c.body and return new Response(...) are unchanged.
  • Wrapping runs for the OpenAPI handler after built-in validators. Route middleware that returns without next() bypasses strict checks; c.json only after the handler returns is also outside the wrapped window.
  • If a response defines multiple JSON-compatible content entries, strictResponse uses the first (object key order).
  • OpenAPI range keys must use spec spelling (1XX5XX, uppercase X).
  • Default body-validation errors include Zod issues; production apps should use hooks to redact or simplify payloads.
  • With either strict flag on, the handler runs inside an async wrapper (minor; may affect stack traces).
  • strictResponse is skipped when the matched response has no JSON Zod schema (e.g. 204 with no body schema).

See README Response validation and Scope and limitations for the full contract; openapi JSDoc summarizes the hooks object and points there.

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Mar 25, 2026

🦋 Changeset detected

Latest commit: ad3c514

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@hono/zod-openapi Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Added tests to validate response behavior for various status codes and response schemas, ensuring strict adherence to defined responses. This includes handling cases where status is set but not declared, and validating response bodies against multiple schemas.
…e validation

Updated comments in the response validation code to enhance clarity, including more descriptive error messages and streamlined documentation for the `ResponseHook` type. This change aims to improve code readability and maintainability.
Introduced a new type, BuiltinStrictValidationJson, to streamline response body type definitions in tests. This change enhances code clarity and reduces redundancy in type assertions for response validation scenarios.
…provements

Enhanced the README to clarify the behavior of body-validation failures and the scope of strict response validation. Added a new test case to verify that strict response validation does not apply when middleware returns a response without calling `next()`. This improves documentation and ensures better understanding of response handling in the OpenAPIHono framework.
@mikan3rd mikan3rd marked this pull request as ready for review March 25, 2026 06:38
mikan3rd and others added 3 commits March 27, 2026 11:40
Refined existing tests to cover additional edge cases in response validation, ensuring comprehensive coverage for various response scenarios. This update enhances the robustness of the validation logic and improves overall test reliability.
@codecov
Copy link
Copy Markdown

codecov bot commented Apr 5, 2026

Codecov Report

❌ Patch coverage is 94.33962% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.76%. Comparing base (52f2d8c) to head (d4f1e54).

Files with missing lines Patch % Lines
packages/zod-openapi/src/index.ts 94.33% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1819      +/-   ##
==========================================
+ Coverage   91.71%   91.76%   +0.05%     
==========================================
  Files         113      113              
  Lines        3803     3900      +97     
  Branches      964      990      +26     
==========================================
+ Hits         3488     3579      +91     
- Misses        283      289       +6     
  Partials       32       32              
Flag Coverage Δ
zod-openapi 93.82% <94.33%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 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.

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