Skip to content

fix(setCookie): handle encode and stringify serialize options#1377

Merged
pi0 merged 1 commit into
mainfrom
fix/serialize
Apr 27, 2026
Merged

fix(setCookie): handle encode and stringify serialize options#1377
pi0 merged 1 commit into
mainfrom
fix/serialize

Conversation

@danielroe

@danielroe danielroe commented Apr 27, 2026

Copy link
Copy Markdown
Member

related to a0761e9

this respects encode/stringify options - these do not seem to be used in the first argument (SetCookie).

(spreading defeats type safety (a ts limitation), but we could update the function signature in cookie-es to disallow accidental spreading if you're interested)

Summary by CodeRabbit

  • Bug Fixes
    • Fixed cookie serialization to properly respect user-supplied encoding functions, ensuring custom encoders are applied correctly without additional re-encoding.

@danielroe
danielroe requested a review from pi0 as a code owner April 27, 2026 20:03
@coderabbitai

coderabbitai Bot commented Apr 27, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The changes refactor setCookie to separate encode and stringify parameters from cookie attributes, passing them as dedicated serializer arguments to serializeCookie. A new test ensures the encode function is respected during serialization.

Changes

Cohort / File(s) Summary
Serialization parameter handling
src/utils/cookie.ts
Modified parameter passing to serializeCookie: encode and stringify are extracted from options and passed as the second argument, with remaining attributes spread into the first argument.
Encode function verification
test/cookies.test.ts
Added test case confirming that setCookie respects user-supplied encode function via serialize options without re-encoding the resulting Set-Cookie header value.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰 A cookie serializer hops with glee,
Encode and stringify now flow so free,
Separated from attributes they roam,
Parameters find their rightful home,
Tests verify the hoppy new way,
Cookie biscuits work better today! 🍪

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main change: fixing how setCookie handles encode and stringify serialize options.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/serialize

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 and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Apr 27, 2026

Copy link
Copy Markdown

Open in StackBlitz

npm i https://pkg.pr.new/h3@1377

commit: d0177a6

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

🧹 Nitpick comments (2)
test/cookies.test.ts (1)

145-152: Good targeted regression test; consider extending coverage to stringify.

The test correctly exercises the fix: with the previous behavior, encode would have been ignored and the default encoder would have re-escaped % to %25, so this would have failed. Nice.

Two optional nits:

  • stringify is the other option extracted in setCookie but is not covered by any test. A small companion test (e.g. setCookie(event, "x", { foo: 1 } as any, { stringify: (v) => JSON.stringify(v) })) would lock in both halves of the fix.
  • For consistency with the surrounding tests, you may want to also assert expect(await result.text()).toBe("200"); so the handler's return path is verified.
     it("respects custom encode option", async () => {
       t.app.get("/", (event) => {
         setCookie(event, "x", "%22true%22", { encode: (v) => v });
         return "200";
       });
       const result = await t.fetch("/");
       expect(result.headers.getSetCookie()).toEqual(["x=%22true%22; Path=/"]);
+      expect(await result.text()).toBe("200");
     });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/cookies.test.ts` around lines 145 - 152, Add a companion test to cover
the `stringify` option in addition to `encode`: create a test (e.g., "respects
custom stringify option") that calls setCookie(event, "x", { foo: 1 } as any, {
stringify: (v) => JSON.stringify(v) }) in the request handler, fetch the route,
assert the Set-Cookie header contains the JSON stringified value, and also
assert the response body via expect(await result.text()).toBe("200");; update
the existing "respects custom encode option" test to include expect(await
result.text()).toBe("200"); so both handler return paths are verified.
src/utils/cookie.ts (1)

88-89: LGTM — clean fix for the encode/stringify pass-through.

Splitting encode/stringify out of the cookie attributes object and forwarding them as the dedicated SerializeOptions argument is the correct fix. The previous code path was effectively dropping these callbacks because cookie-es ignores them when present on the SetCookie attribute object.

Two small notes (non-blocking):

  1. Line 99 just below still uses options || {} while the new line 88 uses options ?? {}. Consider aligning to ?? for consistency (treats only null/undefined as missing, which is the intent here since options is typed as CookieSerializeOptions | undefined).
  2. As you already called out in the PR description, { name, value, path: "/", ...attrs } lets a caller-supplied name/value/path in options silently override the explicit args. Worth following up upstream in cookie-es as you suggested — not a regression in this PR.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/cookie.ts` around lines 88 - 89, The code correctly extracts
encode/stringify into serialize options, but two small fixes remain: (1)
normalize nullish handling by using the nullish coalescing operator for options
everywhere (replace uses of options || {} with options ?? {}) so only
null/undefined fall back; (2) prevent caller-supplied name/value/path in options
from silently overriding explicit args by excluding name, value, and path from
the spread attrs before building the cookie object passed to serializeCookie
(ensure { name, value, path: "/", ...attrsWithoutNameValuePath } is used),
keeping encode/stringify passed as the second argument to serializeCookie.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/utils/cookie.ts`:
- Around line 88-89: The code correctly extracts encode/stringify into serialize
options, but two small fixes remain: (1) normalize nullish handling by using the
nullish coalescing operator for options everywhere (replace uses of options ||
{} with options ?? {}) so only null/undefined fall back; (2) prevent
caller-supplied name/value/path in options from silently overriding explicit
args by excluding name, value, and path from the spread attrs before building
the cookie object passed to serializeCookie (ensure { name, value, path: "/",
...attrsWithoutNameValuePath } is used), keeping encode/stringify passed as the
second argument to serializeCookie.

In `@test/cookies.test.ts`:
- Around line 145-152: Add a companion test to cover the `stringify` option in
addition to `encode`: create a test (e.g., "respects custom stringify option")
that calls setCookie(event, "x", { foo: 1 } as any, { stringify: (v) =>
JSON.stringify(v) }) in the request handler, fetch the route, assert the
Set-Cookie header contains the JSON stringified value, and also assert the
response body via expect(await result.text()).toBe("200");; update the existing
"respects custom encode option" test to include expect(await
result.text()).toBe("200"); so both handler return paths are verified.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c469e1ec-3d99-43e0-a3e8-7258a296103e

📥 Commits

Reviewing files that changed from the base of the PR and between e2f8cbd and d0177a6.

📒 Files selected for processing (2)
  • src/utils/cookie.ts
  • test/cookies.test.ts

@pi0 pi0 changed the title fix: pass serialize options to serialize fix(setCookie): handle encode and stringify serialize options Apr 27, 2026
@pi0
pi0 merged commit 05312b0 into main Apr 27, 2026
8 checks passed
@pi0
pi0 deleted the fix/serialize branch April 27, 2026 20:33
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