Skip to content

fix(cookie): support encode option#1899

Open
lxy2500798479 wants to merge 2 commits into
elysiajs:mainfrom
lxy2500798479:fix/cookie-encode-config
Open

fix(cookie): support encode option#1899
lxy2500798479 wants to merge 2 commits into
elysiajs:mainfrom
lxy2500798479:fix/cookie-encode-config

Conversation

@lxy2500798479

@lxy2500798479 lxy2500798479 commented Jun 1, 2026

Copy link
Copy Markdown

Summary

  • expose encode on cookie options and cookie instances
  • pass encode into cookie parsing/serialization in both AOT and dynamic handlers
  • preserve route-level t.Cookie(..., { encode }) config in dynamic mode

Fixes #1698

Reproduction

Before this change, a custom cookie encoder was ignored and the response emitted name=seminar%20Himari; Path=/:

new Elysia({
  cookie: {
    encode: (value) => value.replaceAll(' ', '+')
  }
}).get('/', ({ cookie: { name } }) => {
  name.value = 'seminar Himari'
})

The expected header is name=seminar+Himari; Path=/.

Boundary report

Covered cases:

  • global cookie config in AOT mode
  • global cookie config in dynamic mode
  • route-level t.Cookie(..., { encode }) in AOT mode
  • route-level t.Cookie(..., { encode }) in dynamic mode
  • per-cookie instance override with cookie.name.encode = ...
  • existing signed, JSON, remove, unchanged, and validator cookie behavior

Tests

  • bun test test/cookie/response.test.ts
  • bun test test/cookie
  • bun test test/validator/cookie.test.ts
  • bun run test:types
  • bun test
  • bun run test:imports

Summary by CodeRabbit

  • New Features

    • Cookie values can now be encoded using custom encoder functions, configurable at the app level, per-route, or per-cookie instance.
    • Route-level encoders override app-level configuration, enabling fine-grained control over cookie serialization.
  • Tests

    • Added comprehensive test coverage for custom cookie encoding across configuration scopes and precedence scenarios.

@coderabbitai

coderabbitai Bot commented Jun 1, 2026

Copy link
Copy Markdown
Contributor

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

Run ID: d15a5099-cf88-4e51-a050-1ebf9041c3f9

📥 Commits

Reviewing files that changed from the base of the PR and between 7a1c7a4 and c24f764.

📒 Files selected for processing (2)
  • src/dynamic-handle.ts
  • test/cookie/response.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/cookie/response.test.ts
  • src/dynamic-handle.ts

Walkthrough

Cookie value encoding is now configurable via an optional encode function in CookieOptions, threaded through the type system validator, resolved per-route in dynamic handling, and injected into optimized code generation to transform cookie values before Set-Cookie serialization.

Changes

Cookie Encoding Support

Layer / File(s) Summary
Cookie encoder contract and instance accessors
src/cookies.ts
CookieOptions adds optional encode?: (value: string) => string field, and Cookie class exposes public get/set encode() accessors for runtime configuration and inspection of the encoder function.
Type system validator integration
src/type-system/index.ts
ElysiaType.Cookie now destructures encode from CookieValidatorOptions parameters and stores it onto the schema's v.config to surface the encoder metadata throughout validation pipelines.
Dynamic handler per-route cookie config resolution
src/dynamic-handle.ts
createDynamicHandler consolidates per-route cookie configuration from hooks.cookie?.config with fallback to validator?.cookie?.config, cleanly sourcing all cookie fields (encode, sign, secrets, domain, path, etc.) and preferring route-level encode when available.
Optimized handler encoder wiring and code generation
src/compose.ts
composeHandler extracts the encode function from cookie metadata, allocates cookieEncode as an injected variable when present, conditionally passes it to parseCookie options, and supplies it as a runtime argument to the generated handler function for cookie value transformation.
Cookie encoding behavior test coverage
test/cookie/response.test.ts
Adds test cases validating custom encode functions (e.g., space → +) work correctly when provided via app config in optimized mode and aot:false, via route-level cookie schema config in both modes, and when assigned to cookie instances during request handling.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes


Possibly related PRs

  • elysiajs/elysia#1794: Both PRs touch cookie handling in src/compose.ts by changing how cookie configuration is sourced/merged and thus which cookie options (including encode) are available to the runtime cookie parsing/serialization path.

Poem

おっ、やっとカスタムクッキーエンコーダかよ〜♡ (¬‿¬)
スペースが「+」になるなんて、君の小さな魔法ね〜♡
バリデータもルートも最適化も、ちゃんと糸で繋いだんだ〜♪ (^ω^)
テストも増やして証明したの、まあ賢いじゃん〜♡
でも調子に乗らないでよね、たかがエンコードだし〜 ( ̄▽ ̄)

🚥 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 'fix(cookie): support encode option' directly and concisely summarizes the main change—adding support for a custom cookie encode option.
Linked Issues check ✅ Passed All code changes implement the requirements from #1698: exposing encode on cookie options, passing it into parsing/serialization in AOT and dynamic handlers, and supporting route/global/per-cookie overrides.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing cookie encode support across compose.ts, cookies.ts, dynamic-handle.ts, type-system/index.ts, and test coverage—no unrelated modifications detected.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/dynamic-handle.ts

Oops! Something went wrong! :(

ESLint: 9.39.4

Error: ESLint configuration in --config » plugin:sonarjs/recommended is invalid:

  • Unexpected top-level property "name".

Referenced from: /.eslintrc.json
at ConfigValidator.validateConfigSchema (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2277:19)
at ConfigArrayFactory._normalizeConfigData (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3123:19)
at ConfigArrayFactory._loadExtendedPluginConfig (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3346:25)
at ConfigArrayFactory._loadExtends (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3259:29)
at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3199:25)
at _normalizeObjectConfigDataBody.next (<anonym

... [truncated 291 characters] ...

/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2952:16)
at createCLIConfigArray (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3768:35)
(node:2) ESLintRCWarning: You are using an eslintrc configuration file, which is deprecated and support will be removed in v10.0.0. Please migrate to an eslint.config.js file. See https://eslint.org/docs/latest/use/configure/migration-guide for details. An eslintrc configuration file is used because you have the ESLINT_USE_FLAT_CONFIG environment variable set to false. If you want to use an eslint.config.js file, remove the environment variable. If you want to find the location of the eslintrc configuration file, use the --debug flag.
(Use node --trace-warnings ... to show where the warning was created)

test/cookie/response.test.ts

Oops! Something went wrong! :(

ESLint: 9.39.4

Error: ESLint configuration in --config » plugin:sonarjs/recommended is invalid:

  • Unexpected top-level property "name".

Referenced from: /.eslintrc.json
at ConfigValidator.validateConfigSchema (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2277:19)
at ConfigArrayFactory._normalizeConfigData (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3123:19)
at ConfigArrayFactory._loadExtendedPluginConfig (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3346:25)
at ConfigArrayFactory._loadExtends (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3259:29)
at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3199:25)
at _normalizeObjectConfigDataBody.next (<anonym

... [truncated 291 characters] ...

/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2952:16)
at createCLIConfigArray (/node_modules/.pnpm/@eslint+eslintrc@3.3.5/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3768:35)
(node:2) ESLintRCWarning: You are using an eslintrc configuration file, which is deprecated and support will be removed in v10.0.0. Please migrate to an eslint.config.js file. See https://eslint.org/docs/latest/use/configure/migration-guide for details. An eslintrc configuration file is used because you have the ESLINT_USE_FLAT_CONFIG environment variable set to false. If you want to use an eslint.config.js file, remove the environment variable. If you want to find the location of the eslintrc configuration file, use the --debug flag.
(Use node --trace-warnings ... to show where the warning was created)


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/dynamic-handle.ts`:
- Around line 479-481: The current precedence for cookie encoder flips
route-level overrides because encode uses app.config.cookie?.encode ??
routeCookieConfig?.encode; change this to prefer the route encoder by using
routeCookieConfig?.encode ?? app.config.cookie?.encode in the same assignment
block (where encode, secrets, sign are set), and add a regression test that sets
both an app-level encoder and a route-level encoder to assert the route-level
encoder is used in dynamic mode.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0fdd09b1-7385-47d2-bda0-45b63c89b73e

📥 Commits

Reviewing files that changed from the base of the PR and between 56310be and 7a1c7a4.

📒 Files selected for processing (5)
  • src/compose.ts
  • src/cookies.ts
  • src/dynamic-handle.ts
  • src/type-system/index.ts
  • test/cookie/response.test.ts

Comment thread src/dynamic-handle.ts Outdated
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.

cookie encode function is not made available to override, while the documentation states that it can be overridden

1 participant