Skip to content

feat(client): support fetch headers in link options#946

Merged
dinwwwh merged 3 commits into
mainfrom
feat/client/support-headers-instance-in-link
Aug 30, 2025
Merged

feat(client): support fetch headers in link options#946
dinwwwh merged 3 commits into
mainfrom
feat/client/support-headers-instance-in-link

Conversation

@dinwwwh
Copy link
Copy Markdown
Member

@dinwwwh dinwwwh commented Aug 29, 2025

Support fetch Headers in headers link option - no more Object.fromEntries

 import { RPCLink } from '@orpc/client/fetch'
 const link = new RPCLink({
   url: `${typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000'}/rpc`,
   headers: async () => {
     if (typeof window !== 'undefined') {
       return {}
     }

    const { headers } = await import('next/headers')
-    return Object.fromEntries(await headers())
+    return await headers()
   },
 })

Summary by CodeRabbit

  • New Features
    • Client and OpenAPI codecs now accept Fetch API Headers and normalize them for requests.
  • Bug Fixes / Behavior
    • Header semantics preserved: cookies merged into a single header; multiple set-cookie values retained; last-event-id merged when present.
  • Documentation
    • Next.js, Nuxt, Solid Start guides and examples updated to pass Headers directly.
  • Tests
    • Added tests validating Fetch Headers handling, including cookie and set-cookie behavior.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Aug 29, 2025
@vercel
Copy link
Copy Markdown

vercel Bot commented Aug 29, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
orpc Ready Ready Preview Comment Aug 30, 2025 2:44am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Aug 29, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds support for passing Fetch API Headers into standard RPC and OpenAPI link codecs by introducing a toStandardHeaders normalization helper, widening codec header option types to accept Headers, normalizing headers early in encode, adding tests, and updating docs/playground examples to forward Headers directly.

Changes

Cohort / File(s) Summary
Docs: Adapters header forwarding
apps/content/docs/adapters/next.md, apps/content/docs/adapters/nuxt.md, apps/content/docs/adapters/solid-start.md
Update examples to forward Headers (or event?.headers) directly to RPCLink headers instead of converting via Object.fromEntries.
Playground: Solid Start usage
playgrounds/solid-start/src/lib/orpc.ts
Forward request Headers (or {}) directly to RPCLink headers option.
Client codec: Standard RPC header handling
packages/client/src/adapters/standard/rpc-link-codec.ts
Widen headers option to accept `StandardHeaders
OpenAPI codec: Standard OpenAPI header handling
packages/openapi-client/src/adapters/standard/openapi-link-codec.ts
Widen headers option to accept `StandardHeaders
Client utils: header normalization
packages/client/src/adapters/standard/utils.ts
Add exported `toStandardHeaders(headers: Headers
Client utils tests
packages/client/src/adapters/standard/utils.test.ts
Add tests for toStandardHeaders covering empty/plain object and Headers inputs and a duck-typed forEach object.
Client codec tests
packages/client/src/adapters/standard/rpc-link-codec.test.ts
Add test "support fetch headers" verifying Headers input is normalized: cookie values merged into one cookie header string and multiple set-cookie values preserved as an array.
OpenAPI codec tests
packages/openapi-client/src/adapters/standard/openapi-link-codec.test.ts
Add tests verifying Headers input handling for OpenAPI codec encode (cookie merge, set-cookie preserved).
Standard-server-fetch: headers iteration
packages/standard-server-fetch/src/headers.ts
Replace for...of iteration with Headers.forEach callback when iterating DOM Headers; merging logic unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App
  participant Codec as Standard*LinkCodec
  participant Utils as toStandardHeaders
  participant HTTP as HTTP Transport

  App->>Codec: encode(path, input, { headers: Headers | Record })
  Codec->>Utils: toStandardHeaders(headers)
  Utils-->>Codec: StandardHeaders (plain object)
  alt last-event-id provided
    Codec->>Codec: merge last-event-id into headers
  end
  Codec->>HTTP: Build request with normalized headers (cookie merged, set-cookie preserved)
  HTTP-->>App: Prepared request
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • unnoq/orpc#266 — Related changes to StandardRPCLinkCodec header construction and immediate last-event-id merging.
  • unnoq/orpc#338 — Related modifications to codec option types and encode behavior in standard/OpenAPI codecs.
  • unnoq/orpc#562 — Related Solid Start / adapter examples adjusting how request headers are forwarded to RPCLink.

Suggested labels

size:L

Poem

A hop, a nibble, headers set straight,
I stitch cookies so they share one plate.
Set-Cookie lines kept twinkling and true,
From Fetch to standard I carry them through.
Ears perked, I normalize — off with a cheer! 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 21fcc81 and b667337.

📒 Files selected for processing (2)
  • packages/client/src/adapters/standard/utils.test.ts (1 hunks)
  • packages/client/src/adapters/standard/utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/client/src/adapters/standard/utils.ts
  • packages/client/src/adapters/standard/utils.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: publish-commit
  • GitHub Check: test
  • GitHub Check: lint
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/client/support-headers-instance-in-link

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @unnoq, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the client-side RPCLink configuration by enabling direct support for Headers objects in the headers option. This simplifies header management, eliminating the need for manual conversion from Headers to plain objects, and updates relevant documentation and test cases to reflect this improvement.

Highlights

  • Direct Headers Support: The RPCLink headers option now directly accepts Headers objects, alongside existing plain object headers.
  • Simplified Header Handling: Eliminates the need for Object.fromEntries when working with Headers instances from environments like Next.js or SolidStart.
  • Internal Header Conversion: Introduces a new utility function toStandardHeaders to internally convert Headers objects to the library's StandardHeaders format.
  • Documentation Updates: Examples in Next.js, Nuxt, and SolidStart documentation have been updated to leverage the new direct Headers support.
  • Comprehensive Testing: New test cases have been added to ensure proper handling and conversion of Headers objects within the client and OpenAPI link codecs.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@codecov
Copy link
Copy Markdown

codecov Bot commented Aug 29, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds support for using Headers objects directly in link options, which simplifies header management in various adapters like Next.js, Nuxt, and Solid Start. The changes are well-structured and include new tests for the functionality. My main feedback is regarding the handling of multiple cookie headers, which seems to be incorrect in a dependency and will cause the new tests to fail. I've provided a suggestion to fix this within the client utility function.

Comment thread packages/client/src/adapters/standard/utils.ts Outdated
@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented Aug 29, 2025

More templates

@orpc/arktype

npm i https://pkg.pr.new/@orpc/arktype@946

@orpc/client

npm i https://pkg.pr.new/@orpc/client@946

@orpc/contract

npm i https://pkg.pr.new/@orpc/contract@946

@orpc/experimental-durable-event-iterator

npm i https://pkg.pr.new/@orpc/experimental-durable-event-iterator@946

@orpc/hey-api

npm i https://pkg.pr.new/@orpc/hey-api@946

@orpc/interop

npm i https://pkg.pr.new/@orpc/interop@946

@orpc/json-schema

npm i https://pkg.pr.new/@orpc/json-schema@946

@orpc/nest

npm i https://pkg.pr.new/@orpc/nest@946

@orpc/openapi

npm i https://pkg.pr.new/@orpc/openapi@946

@orpc/openapi-client

npm i https://pkg.pr.new/@orpc/openapi-client@946

@orpc/otel

npm i https://pkg.pr.new/@orpc/otel@946

@orpc/react

npm i https://pkg.pr.new/@orpc/react@946

@orpc/react-query

npm i https://pkg.pr.new/@orpc/react-query@946

@orpc/experimental-react-swr

npm i https://pkg.pr.new/@orpc/experimental-react-swr@946

@orpc/server

npm i https://pkg.pr.new/@orpc/server@946

@orpc/shared

npm i https://pkg.pr.new/@orpc/shared@946

@orpc/solid-query

npm i https://pkg.pr.new/@orpc/solid-query@946

@orpc/standard-server

npm i https://pkg.pr.new/@orpc/standard-server@946

@orpc/standard-server-aws-lambda

npm i https://pkg.pr.new/@orpc/standard-server-aws-lambda@946

@orpc/standard-server-fetch

npm i https://pkg.pr.new/@orpc/standard-server-fetch@946

@orpc/standard-server-node

npm i https://pkg.pr.new/@orpc/standard-server-node@946

@orpc/standard-server-peer

npm i https://pkg.pr.new/@orpc/standard-server-peer@946

@orpc/svelte-query

npm i https://pkg.pr.new/@orpc/svelte-query@946

@orpc/tanstack-query

npm i https://pkg.pr.new/@orpc/tanstack-query@946

@orpc/trpc

npm i https://pkg.pr.new/@orpc/trpc@946

@orpc/valibot

npm i https://pkg.pr.new/@orpc/valibot@946

@orpc/vue-colada

npm i https://pkg.pr.new/@orpc/vue-colada@946

@orpc/vue-query

npm i https://pkg.pr.new/@orpc/vue-query@946

@orpc/zod

npm i https://pkg.pr.new/@orpc/zod@946

commit: b667337

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (6)
apps/content/docs/adapters/nuxt.md (1)

60-60: Pass Headers instance directly: good; add a safe fallback.

Using event?.headers aligns with the PR intent. Consider a defensive fallback to avoid passing undefined on the client.

-    headers: event?.headers,
+    headers: event?.headers ?? {},
apps/content/docs/adapters/next.md (1)

104-106: Drop unnecessary await on headers().

next/headers’s headers() is synchronous; removing await avoids implying it’s async.

-    const { headers } = await import('next/headers')
-    return await headers()
+    const { headers } = await import('next/headers')
+    return headers()
packages/client/src/adapters/standard/utils.ts (1)

3-3: Confirm client-bundle safety of @orpc/standard-server-fetch import.

Ensure this import is tree-shakeable and browser-safe (no Node-only side effects). If not, consider moving the converter to a shared, isomorphic utility.

packages/client/src/adapters/standard/rpc-link-codec.test.ts (1)

107-125: Add a case for lastEventId with Headers.

Ensure mergeStandardHeaders runs when headers is a Headers instance.

Example test to add:

it('support fetch headers + last-event-id', async () => {
  const headers = new Headers([['cookie', 'a=1']])
  const codec = new StandardRPCLinkCodec(serializer, { url: 'http://localhost:3000', headers })
  const req = await codec.encode(['test'], 'input', { context: {}, lastEventId: '9' })
  expect(req.headers['cookie']).toBe('a=1')
  expect(req.headers['last-event-id']).toBe('9')
})
packages/client/src/adapters/standard/utils.test.ts (1)

9-13: Broaden tests to cover Headers-like (cross-realm) objects.

Next.js ReadonlyHeaders are not instanceof global Headers; current tests won’t catch that path.

Add:

it('toStandardHeaders with headers-like object', () => {
  const headersLike = {
    map: new Map<string, string[]>([['cookie', ['a=1','b=2']], ['set-cookie', ['a1=1','b1=2']]]),
    forEach(cb: any) { for (const [k, arr] of this.map) for (const v of arr) cb(v, k) },
    [Symbol.iterator]() { return this.map[Symbol.iterator]() },
  } as any
  expect(toStandardHeaders(headersLike)).toEqual({ cookie: 'a=1; b=2', 'set-cookie': ['a1=1', 'b1=2'] })
})
packages/openapi-client/src/adapters/standard/openapi-link-codec.test.ts (1)

53-71: Add coverage for lastEventId + Headers and for headers function returning a Headers instance.

Confirms both async Value and merge behavior.

Examples to add:

it('support fetch headers via function + lastEventId', async () => {
  const headers = new Headers([['cookie', 'a=1']])
  const codec = new StandardOpenapiLinkCodec({ ping: oc }, serializer, { url: 'http://localhost:3000', headers: async () => headers })
  const req = await codec.encode(['ping'], 'input', { context: {}, lastEventId: '7' })
  expect(req.headers['cookie']).toBe('a=1')
  expect(req.headers['last-event-id']).toBe('7')
})
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ad4a1f5 and 99f686c.

📒 Files selected for processing (10)
  • apps/content/docs/adapters/next.md (1 hunks)
  • apps/content/docs/adapters/nuxt.md (1 hunks)
  • apps/content/docs/adapters/solid-start.md (1 hunks)
  • packages/client/src/adapters/standard/rpc-link-codec.test.ts (1 hunks)
  • packages/client/src/adapters/standard/rpc-link-codec.ts (3 hunks)
  • packages/client/src/adapters/standard/utils.test.ts (1 hunks)
  • packages/client/src/adapters/standard/utils.ts (1 hunks)
  • packages/openapi-client/src/adapters/standard/openapi-link-codec.test.ts (1 hunks)
  • packages/openapi-client/src/adapters/standard/openapi-link-codec.ts (3 hunks)
  • playgrounds/solid-start/src/lib/orpc.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (6)
packages/client/src/adapters/standard/utils.ts (2)
packages/client/src/types.ts (1)
  • HTTPPath (3-3)
packages/standard-server/src/types.ts (1)
  • StandardHeaders (1-3)
packages/client/src/adapters/standard/rpc-link-codec.test.ts (3)
packages/standard-server-fetch/src/request.ts (2)
  • headers (13-17)
  • headers (18-20)
packages/standard-server-fetch/src/response.ts (2)
  • headers (27-31)
  • headers (32-34)
packages/client/src/adapters/standard/rpc-link-codec.ts (1)
  • StandardRPCLinkCodec (45-145)
packages/openapi-client/src/adapters/standard/openapi-link-codec.ts (4)
packages/shared/src/value.ts (2)
  • Value (1-1)
  • value (3-12)
packages/standard-server/src/types.ts (1)
  • StandardHeaders (1-3)
packages/client/src/adapters/standard/utils.ts (1)
  • toStandardHeaders (10-19)
packages/standard-server/src/utils.ts (1)
  • mergeStandardHeaders (28-49)
packages/client/src/adapters/standard/utils.test.ts (1)
packages/client/src/adapters/standard/utils.ts (2)
  • toHttpPath (6-8)
  • toStandardHeaders (10-19)
packages/openapi-client/src/adapters/standard/openapi-link-codec.test.ts (2)
packages/openapi-client/src/adapters/standard/openapi-link-codec.ts (1)
  • StandardOpenapiLinkCodec (34-247)
packages/contract/src/builder.ts (1)
  • oc (189-198)
packages/client/src/adapters/standard/rpc-link-codec.ts (7)
packages/shared/src/value.ts (2)
  • Value (1-1)
  • value (3-12)
packages/standard-server/src/types.ts (1)
  • StandardHeaders (1-3)
packages/client/src/types.ts (1)
  • ClientOptions (8-12)
packages/standard-server-fetch/src/request.ts (2)
  • headers (13-17)
  • headers (18-20)
packages/standard-server-fetch/src/response.ts (2)
  • headers (27-31)
  • headers (32-34)
packages/client/src/adapters/standard/utils.ts (1)
  • toStandardHeaders (10-19)
packages/standard-server/src/utils.ts (1)
  • mergeStandardHeaders (28-49)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: test
  • GitHub Check: publish-commit
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (10)
playgrounds/solid-start/src/lib/orpc.ts (1)

18-19: LGTM: forwards Fetch Headers (SSR) and {} in the browser.

This matches the widened headers option and keeps SSR/browser parity.

apps/content/docs/adapters/solid-start.md (1)

64-65: LGTM: pass through Headers directly.

Forwarding getRequestEvent()?.request.headers without converting to an object is consistent with the new API.

packages/client/src/adapters/standard/rpc-link-codec.test.ts (1)

107-125: Good coverage for Fetch Headers normalization.

Asserts match the expected cookie join and set-cookie array semantics.

packages/client/src/adapters/standard/utils.test.ts (1)

1-1: Import looks correct.

Matches the new export surface.

packages/client/src/adapters/standard/rpc-link-codec.ts (2)

9-9: Importing toStandardHeaders is appropriate and consistent with OpenAPI codec.


42-42: Public option widened to Headers | StandardHeaders.

API change is reasonable; ensure docs/changelog note this (minor).

packages/openapi-client/src/adapters/standard/openapi-link-codec.test.ts (1)

53-71: Good parity test with RPC: verifies cookie join and set-cookie array.

packages/openapi-client/src/adapters/standard/openapi-link-codec.ts (3)

8-8: Import of toStandardHeaders aligns with client RPC codec.


27-27: Headers option widened to Headers | StandardHeaders.

Looks good; consider noting that input.headers (in detailed mode) still expects StandardHeaders only.


53-53: Computing baseUrl after header normalization is fine; no behavior change.

Comment thread packages/client/src/adapters/standard/rpc-link-codec.ts
Comment thread packages/client/src/adapters/standard/utils.ts
Comment thread packages/openapi-client/src/adapters/standard/openapi-link-codec.ts
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Aug 30, 2025
@dinwwwh dinwwwh merged commit 216e5a5 into main Aug 30, 2025
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant