Skip to content

feat(cli): add openapi suppport in orpc - #563

Merged
AmanVarshney01 merged 3 commits into
mainfrom
orpc-openapi
Sep 4, 2025
Merged

AmanVarshney01 merged 3 commits into
mainfrom
orpc-openapi

Conversation

@AmanVarshney01

@AmanVarshney01 AmanVarshney01 commented Sep 4, 2025 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • ORPC templates now expose OpenAPI-powered API docs/schemas across Next, Express, Fastify, Hono, and Elysia; Next.js RPC route supports GET/POST/PUT/PATCH/DELETE.
  • Documentation

    • Post-install instructions for ORPC projects now include a link to the OpenAPI docs endpoint.
  • Chores

    • Added OpenAPI-related ORPC dependencies.
    • Alchemy deployment setups no longer inject a “dev” script; only “deploy” and “destroy” are added.

@coderabbitai

coderabbitai Bot commented Sep 4, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds OpenAPI support for ORPC across CLI templates and helpers, updates dependency map to include @orpc/openapi and @orpc/zod, appends ORPC OpenAPI post-install messaging, introduces dual rpc/api handlers in multiple server templates, and removes injected Alchemy dev scripts from several deployment setups.

Changes

Cohort / File(s) Summary of changes
CLI constants & core
apps/cli/src/constants.ts, apps/cli/src/helpers/core/api-setup.ts, apps/cli/src/helpers/core/post-installation.ts
Adds @orpc/openapi and @orpc/zod to dependencyVersionMap; expands ORPC server dependencies to include @orpc/openapi and @orpc/zod; post-install output now includes OpenAPI (Scalar UI) URL for ORPC when applicable.
Alchemy deployment setups
apps/cli/src/helpers/deployment/alchemy/alchemy-*-setup.ts (next, nuxt, react-router, solid, svelte, tanstack-router, tanstack-start)
Removed forced injection of dev: "alchemy dev" into web app package.json; still adds deploy and destroy when applicable and preserves existing scripts.
Next.js ORPC route template
apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs
Adds OpenAPIHandler with OpenAPIReferencePlugin and ZodToJsonSchemaConverter; splits handling into rpcHandler and apiHandler; routes try /rpc then /rpc/api; exports GET/POST/PUT/PATCH/DELETE; returns 404 when unmatched.
Backend server templates (ORPC + OpenAPI)
apps/cli/templates/backend/server/*/src/index.ts.hbs (elysia, express, fastify, hono)
Introduces apiHandler (OpenAPIHandler) alongside rpcHandler; integrates OpenAPIReferencePlugin + ZodToJsonSchemaConverter; request flow attempts /rpc first then /api; adds onError interceptors and relevant imports; TRPC paths preserved.
Hono template exports
apps/cli/templates/backend/server/hono/src/index.ts.hbs
Adds exported constants apiHandler and rpcHandler initialized with OpenAPIHandler and RPCHandler respectively (with interceptors/plugins configured).

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant C as Client
  participant S as Server
  participant R as rpcHandler (/rpc...)
  participant A as apiHandler (/api... or /rpc/api)
  participant F as Fallback/next

  C->>S: HTTP request
  S->>R: rpcHandler.handle(request, prefix=/rpc)
  R-->>S: { matched?, response }
  alt matched by RPC
    S-->>C: RPC response
  else not matched
    S->>A: apiHandler.handle(request, prefix=/api or /rpc/api)
    A-->>S: { matched?, response }
    alt matched by API
      S-->>C: OpenAPI/schema or API response
    else not matched
      S->>F: next()
      F-->>C: 404 / downstream
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

In a burrow of bytes I nibble and hop,
Two handlers now dance where once was one stop.
Zod maps the schema, OpenAPI shines,
Dev script withdrawn—deploy and destroy signs.
I twitch my nose—templates aligned, hop on time! 🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch orpc-openapi

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.

@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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/cli/templates/backend/server/fastify/src/index.ts.hbs (1)

68-75: createContext used unconditionally but imported only with better-auth – breaks generation when auth ≠ "better-auth".

This will crash/TS-error when auth isn’t “better-auth”. Use the same conditional pattern as the Next/Hono templates.

Apply:

-      const { matched } = await rpcHandler.handle(req, res, {
-        context: await createContext(req.headers),
+      const { matched } = await rpcHandler.handle(req, res, {
+        context: {{#if (eq auth "better-auth")}}await createContext(req.headers){{else}}{}{{/if}},
         prefix: "/rpc",
       });
@@
-      const apiResult = await apiHandler.handle(req, res, {
-        context: await createContext(req.headers),
+      const apiResult = await apiHandler.handle(req, res, {
+        context: {{#if (eq auth "better-auth")}}await createContext(req.headers){{else}}{}{{/if}},
         prefix: "/api",
       });

Optional minor: avoid double context creation by computing once after routing decision (e.g., check req.url for /rpc vs /api) and reuse.

Also applies to: 77-85

🧹 Nitpick comments (8)
apps/cli/src/helpers/core/post-installation.ts (1)

163-169: Verify OpenAPI UI URL; likely needs “/reference” suffix.

With OpenAPIReferencePlugin, the interactive UI is typically served under “/reference” (and the JSON under “/openapi.json”). Please confirm the actual mount paths in the templates; if so, adjust the post-install copy to avoid sending users to a 404.

Proposed tweak:

-        output += `${pc.cyan("•")} OpenAPI (Scalar UI): http://localhost:3000/rpc/api\n`;
+        output += `${pc.cyan("•")} OpenAPI (Scalar UI): http://localhost:3000/rpc/api/reference\n`;
...
-        output += `${pc.cyan("•")} OpenAPI (Scalar UI): http://localhost:3000/api\n`;
+        output += `${pc.cyan("•")} OpenAPI (Scalar UI): http://localhost:3000/api/reference\n`;

Optionally also add the spec URL:

+        output += `${pc.cyan("•")} OpenAPI JSON: http://localhost:3000/rpc/api/openapi.json\n`;

and

+        output += `${pc.cyan("•")} OpenAPI JSON: http://localhost:3000/api/openapi.json\n`;
apps/cli/templates/backend/server/elysia/src/index.ts.hbs (1)

60-66: Prefer function syntax over arrows for handlers.

Repo guidelines ask for normal functions in JS/TS. Also, you can avoid recomputing context twice by reusing it for both handlers.

-  .all('/rpc*', async (context) => {
+  .all('/rpc*', async function (context) {
     const { response } = await rpcHandler.handle(context.request, {
       prefix: '/rpc',
       context: await createContext({ context })
     })
     return response ?? new Response('Not Found', { status: 404 })
   })
-  .all('/api*', async (context) => {
-    const { response } = await apiHandler.handle(context.request, {
+  .all('/api*', async function (context) {
+    // Optional: if createContext() is heavy, compute once and reuse.
+    const ctx = await createContext({ context });
+    const { response } = await apiHandler.handle(context.request, {
       prefix: '/api',
-      context: await createContext({ context })
+      context: ctx
     })
     return response ?? new Response('Not Found', { status: 404 })
   })

Additionally, given OpenAPI routes commonly use PUT/PATCH/DELETE, consider expanding CORS methods above:

-      methods: ["GET", "POST", "OPTIONS"],
+      methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],

Also applies to: 67-74

apps/cli/templates/backend/server/express/src/index.ts.hbs (1)

65-88: Use function syntax and avoid duplicate context creation.

Follow repo style (no arrows) and compute context once for both handlers to cut overhead.

-app.use(async (req, res, next) => {
+app.use(async function (req, res, next) {
+  {{#if (eq auth "better-auth")}}
+  const ctx = await createContext({ req });
+  {{else}}
+  const ctx = {};
+  {{/if}}
   const rpcResult = await rpcHandler.handle(req, res, {
     prefix: "/rpc",
-    {{#if (eq auth "better-auth")}}
-    context: await createContext({ req }),
-    {{else}}
-    context: {},
-    {{/if}}
+    context: ctx,
   });
   if (rpcResult.matched) return;

   const apiResult = await apiHandler.handle(req, res, {
     prefix: "/api",
-    {{#if (eq auth "better-auth")}}
-    context: await createContext({ req }),
-    {{else}}
-    context: {},
-    {{/if}}
+    context: ctx,
   });
   if (apiResult.matched) return;

   next();
});

Also, consider broadening CORS methods to support typical OpenAPI operations:

-    methods: ["GET", "POST", "OPTIONS"],
+    methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
apps/cli/templates/backend/server/fastify/src/index.ts.hbs (2)

46-55: CORS headers mismatch vs other parts; include X-Requested-With.

Align ORPC CORS headers with common defaults to avoid preflight surprises from some clients.

Apply:

     new CORSPlugin({
       origin: process.env.CORS_ORIGIN,
       credentials: true,
-      allowHeaders: ["Content-Type", "Authorization"],
+      allowHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
     }),

56-63: /api (OpenAPI) currently bypasses Fastify CORS; add CORS at the handler-level.

Since /api is handled before fastifyCors, it won’t get CORS headers. If the OpenAPI endpoints or UI are accessed cross-origin, add CORS to apiHandler as well.

If supported by OpenAPIHandler plugins in your version, do:

 const apiHandler = new OpenAPIHandler(appRouter, {
   plugins: [
     new OpenAPIReferencePlugin({
       schemaConverters: [new ZodToJsonSchemaConverter()],
     }),
+    new CORSPlugin({
+      origin: process.env.CORS_ORIGIN,
+      credentials: true,
+      allowHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
+    }),
   ],
 });

If CORSPlugin isn’t accepted by OpenAPIHandler, consider a tiny wrapper that sets CORS headers on res when apiHandler matches.

apps/cli/templates/backend/server/hono/src/index.ts.hbs (1)

70-92: Return the Response directly instead of rebuilding via c.newResponse.

c.newResponse(rpcResult.response.body, rpcResult.response) passes a Response as ResponseInit; it works structurally but is unnecessary and may affect streaming semantics. Returning the Response is simpler and avoids accidental header/body mismatches.

Apply:

-  if (rpcResult.matched) {
-    return c.newResponse(rpcResult.response.body, rpcResult.response);
-  }
+  if (rpcResult.matched) {
+    return rpcResult.response;
+  }
@@
-  if (apiResult.matched) {
-    return c.newResponse(apiResult.response.body, apiResult.response);
-  }
+  if (apiResult.matched) {
+    return apiResult.response;
+  }
apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (2)

21-26: Confirm adapter return shape (‘response’ vs ‘matched’) for consistency.

Other templates use matched; here you check response. If the fetch adapter guarantees response only when matched, it’s fine. Otherwise, prefer a matched gate to avoid returning undefined.

Potential tweak:

-  if (rpcResult.response) return rpcResult.response
+  if (rpcResult.matched) return rpcResult.response

27-34: Same note for api handler and minor path guard.

  • Verify apiResult.response gating as above.
  • Optional: short-circuit by checking req.nextUrl.pathname.startsWith('/rpc/api') before invoking apiHandler to skip extra work on non-API paths.
-  const apiResult = await apiHandler.handle(req, {
+  // Optional early guard:
+  // if (!req.nextUrl.pathname.startsWith('/rpc/api')) return new Response('Not found', { status: 404 })
+  const apiResult = await apiHandler.handle(req, {
     prefix: '/rpc/api',
     context: {{#if (eq auth "better-auth")}}await createContext(req){{else}}{}{{/if}},
   })
-  if (apiResult.response) return apiResult.response
+  if (apiResult.matched) return apiResult.response
📜 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 50a1b94 and 34eb1c1.

📒 Files selected for processing (15)
  • apps/cli/src/constants.ts (1 hunks)
  • apps/cli/src/helpers/core/api-setup.ts (1 hunks)
  • apps/cli/src/helpers/core/post-installation.ts (2 hunks)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-next-setup.ts (0 hunks)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-nuxt-setup.ts (0 hunks)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-react-router-setup.ts (0 hunks)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-solid-setup.ts (0 hunks)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-svelte-setup.ts (0 hunks)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-tanstack-router-setup.ts (0 hunks)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-tanstack-start-setup.ts (0 hunks)
  • apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (1 hunks)
  • apps/cli/templates/backend/server/elysia/src/index.ts.hbs (3 hunks)
  • apps/cli/templates/backend/server/express/src/index.ts.hbs (2 hunks)
  • apps/cli/templates/backend/server/fastify/src/index.ts.hbs (4 hunks)
  • apps/cli/templates/backend/server/hono/src/index.ts.hbs (2 hunks)
💤 Files with no reviewable changes (7)
  • apps/cli/src/helpers/deployment/alchemy/alchemy-solid-setup.ts
  • apps/cli/src/helpers/deployment/alchemy/alchemy-svelte-setup.ts
  • apps/cli/src/helpers/deployment/alchemy/alchemy-tanstack-router-setup.ts
  • apps/cli/src/helpers/deployment/alchemy/alchemy-react-router-setup.ts
  • apps/cli/src/helpers/deployment/alchemy/alchemy-nuxt-setup.ts
  • apps/cli/src/helpers/deployment/alchemy/alchemy-next-setup.ts
  • apps/cli/src/helpers/deployment/alchemy/alchemy-tanstack-start-setup.ts
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)

**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)

In TypeScript, use type aliases (type) instead of interface for type definitions

Files:

  • apps/cli/src/helpers/core/api-setup.ts
  • apps/cli/src/constants.ts
  • apps/cli/src/helpers/core/post-installation.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)

**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
Use Bun.serve() for HTTP/WebSockets; do not use express
Use bun:sqlite for SQLite; do not use better-sqlite3
Use Bun.redis for Redis; do not use ioredis
Use Bun.sql for Postgres; do not use pg or postgres.js
Use built-in WebSocket; do not use ws
Prefer Bun.file over node:fs readFile/writeFile
Use Bun.$ instead of execa for shelling out

Files:

  • apps/cli/src/helpers/core/api-setup.ts
  • apps/cli/src/constants.ts
  • apps/cli/src/helpers/core/post-installation.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/better-t-stack-repo.mdc)

Use normal (function declaration) syntax; do not use arrow functions

Files:

  • apps/cli/src/helpers/core/api-setup.ts
  • apps/cli/src/constants.ts
  • apps/cli/src/helpers/core/post-installation.ts
🔇 Additional comments (13)
apps/cli/src/helpers/core/post-installation.ts (1)

17-17: Config destructuring looks good.

Including api in the config read is correct and consistent with downstream usage.

apps/cli/src/helpers/core/api-setup.ts (1)

57-64: ORPC server deps extended correctly.

Adding @orpc/openapi and @orpc/zod aligns with the new handlers in templates.

Please double-check that the added packages exist in dependencyVersionMap (they do) and that the versions are compatible with the imports used in templates (node vs fetch adapters and zod4 converter).

apps/cli/src/constants.ts (1)

115-116: Version pins added for @orpc/openapi and @orpc/zod.

Looks consistent with other @orpc/* pins (all ^1.8.6).

Consider running your update-deps flow (taze) to ensure these are the latest compatible versions before release.

apps/cli/templates/backend/server/elysia/src/index.ts.hbs (2)

13-16: OpenAPI imports align with usage.

Using fetch adapters here is appropriate for Elysia; zod4 converter matches the plugin setup.


25-33: Handler setup is clean and matches the router.

Instantiation outside the route blocks avoids per-request allocation.

apps/cli/templates/backend/server/express/src/index.ts.hbs (2)

8-11: OpenAPI imports for Node adapter look correct.

Matches Express’ req/res adapter usage.


56-64: Handler construction is fine.

Single instances reused across requests is ideal.

apps/cli/templates/backend/server/fastify/src/index.ts.hbs (1)

12-15: Correct imports for ORPC OpenAPI (node adapter).

Adapter choices look right for Fastify (node).

apps/cli/templates/backend/server/hono/src/index.ts.hbs (3)

8-11: Correct imports for ORPC OpenAPI (fetch adapter).

Adapter selections match Hono’s fetch environment.


60-67: apiHandler configuration looks good.

Zod v4 converter + reference plugin is the expected setup.


68-69: rpcHandler instantiation looks good.

No issues spotted.

apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (2)

5-8: Correct OpenAPI imports for Next (fetch adapter).

Looks consistent with other templates.


11-18: Handler setup reads well.

Using module-scoped handlers avoids per-request instantiation.

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

If can, please add there line into RPCHandler, and OpenAPIHandler by default.

import { onError } from '@orpc/server' // or @orpc/client
Image

@AmanVarshney01
AmanVarshney01 merged commit a276add into main Sep 4, 2025
@AmanVarshney01
AmanVarshney01 deleted the orpc-openapi branch September 4, 2025 09:38

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/cli/templates/backend/server/fastify/src/index.ts.hbs (1)

79-96: Auth context gating and error handling in serverFactory.

  • For auth !== "better-auth", createContext isn’t imported but is still called — this will break generation.
  • Uncaught errors in the raw createServer handler can tear down the process or leave sockets hanging.

Apply this diff to gate context like other templates and add a try/catch with a safe 500:

-    const server = createServer(async (req, res) => {
-      const { matched } = await rpcHandler.handle(req, res, {
-        context: await createContext(req.headers),
-        prefix: "/rpc",
-      });
-
-      if (matched) {
-        return;
-      }
-
-      const apiResult = await apiHandler.handle(req, res, {
-        context: await createContext(req.headers),
-        prefix: "/api",
-      });
-
-      if (apiResult.matched) {
-        return;
-      }
-
-      fastifyHandler(req, res);
-    });
+    const server = createServer(async (req, res) => {
+      try {
+        let ctxPromise;
+        const getCtx = () =>
+          (ctxPromise ??=
+            {{#if (eq auth "better-auth")}}
+            createContext(req.headers)
+            {{else}}
+            Promise.resolve({})
+            {{/if}});
+
+        const { matched } = await rpcHandler.handle(req, res, {
+          context: await getCtx(),
+          prefix: "/rpc",
+        });
+        if (matched) return;
+
+        const apiResult = await apiHandler.handle(req, res, {
+          context: await getCtx(),
+          prefix: "/api",
+        });
+        if (apiResult.matched) return;
+
+        fastifyHandler(req, res);
+      } catch (err) {
+        fastify.log.error({ err }, "Unhandled error in ORPC dispatch");
+        if (!res.headersSent) {
+          res.statusCode = 500;
+          res.end("Internal Server Error");
+        } else {
+          try { res.end(); } catch {}
+        }
+      }
+    });
🧹 Nitpick comments (4)
apps/cli/templates/backend/server/elysia/src/index.ts.hbs (1)

72-77: Use Elysia’s native 404 helper for consistency.

Elsewhere you use context.error(405). Align 404s to the same style.

-    return response ?? new Response('Not Found', { status: 404 })
+    return response ?? context.error(404)

Apply to both /rpc* and /api* blocks.

Also applies to: 79-85

apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (1)

12-18: Deduplicate identical error interceptors.

Define interceptors once and reuse across handlers.

-const rpcHandler = new RPCHandler(appRouter, {
-  interceptors: [
-    onError((error) => {
-      console.error(error)
-    }),
-  ],
-})
+const interceptors = [
+  onError((error) => {
+    console.error(error)
+  }),
+]
+const rpcHandler = new RPCHandler(appRouter, { interceptors })
 
-const apiHandler = new OpenAPIHandler(appRouter, {
+const apiHandler = new OpenAPIHandler(appRouter, {
   plugins: [
     new OpenAPIReferencePlugin({
       schemaConverters: [new ZodToJsonSchemaConverter()],
     }),
   ],
-  interceptors: [
-    onError((error) => {
-      console.error(error)
-    }),
-  ],
+  interceptors,
 })

Also applies to: 19-30

apps/cli/templates/backend/server/hono/src/index.ts.hbs (2)

90-101: Return the handler’s Response directly.

No need to re-wrap with c.newResponse; returning the Response preserves headers/status and avoids an extra allocation.

-  if (rpcResult.matched) {
-    return c.newResponse(rpcResult.response.body, rpcResult.response);
-  }
+  if (rpcResult.matched) {
+    return rpcResult.response;
+  }
 ...
-  if (apiResult.matched) {
-    return c.newResponse(apiResult.response.body, apiResult.response);
-  }
+  if (apiResult.matched) {
+    return apiResult.response;
+  }

61-72: DRY up identical error interceptors.

Factor the onError interceptor and reuse in both handler configs.

- export const apiHandler = new OpenAPIHandler(appRouter, {
+ const interceptors = [
+   onError((error) => {
+     console.error(error);
+   }),
+ ];
+ export const apiHandler = new OpenAPIHandler(appRouter, {
   plugins: [
     new OpenAPIReferencePlugin({
       schemaConverters: [new ZodToJsonSchemaConverter()],
     }),
   ],
-  interceptors: [
-    onError((error) => {
-      console.error(error);
-    }),
-  ],
+  interceptors,
 });
 
-export const rpcHandler = new RPCHandler(appRouter, {
-  interceptors: [
-    onError((error) => {
-      console.error(error);
-    }),
-  ],
-});
+export const rpcHandler = new RPCHandler(appRouter, { interceptors });

Also applies to: 74-80

📜 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 34eb1c1 and b4adf2e.

📒 Files selected for processing (5)
  • apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (1 hunks)
  • apps/cli/templates/backend/server/elysia/src/index.ts.hbs (3 hunks)
  • apps/cli/templates/backend/server/express/src/index.ts.hbs (2 hunks)
  • apps/cli/templates/backend/server/fastify/src/index.ts.hbs (3 hunks)
  • apps/cli/templates/backend/server/hono/src/index.ts.hbs (2 hunks)
🔇 Additional comments (9)
apps/cli/templates/backend/server/express/src/index.ts.hbs (3)

8-13: OpenAPI + ORPC imports look correct for Express.

Matches node adapters and aligns with router import. No issues.


57-63: Good: RPC handler with error interceptor.

Interceptors will prevent silent failures and aid debugging.


64-75: Good: OpenAPI handler configured with reference plugin + zod converter.

Solid baseline for schema generation.

apps/cli/templates/backend/server/elysia/src/index.ts.hbs (2)

13-17: Imports are consistent with fetch adapters.

Correct pairing of OpenAPIHandler/RPCHandler with fetch variants and onError.


26-44: Handlers and interceptors setup looks good.

OpenAPI plugin + zod converter wired correctly; error logging present.

apps/cli/templates/backend/server/fastify/src/index.ts.hbs (2)

12-18: Imports look correct for node adapters and plugins.

Good inclusion of onError and OpenAPI/zod pieces.


47-61: RPC handler configuration is solid.

CORS is handled inside the raw HTTP path; error interceptor attached.

apps/cli/templates/api/orpc/server/next/src/app/rpc/[...all]/route.ts.hbs (1)

5-7: Zod converter consistency verified; ensure Zod v4 dep All templates import ZodToJsonSchemaConverter from @orpc/zod/zod4, and @orpc/zod is pinned to ^1.8.6 in your constants. Confirm that the generated package.json also declares a matching zod v4.x dependency to avoid mismatched major versions.

apps/cli/templates/backend/server/hono/src/index.ts.hbs (1)

95-96: Confirm docs include both /api and /rpc/api. Post-install already prints

No examples in README.md currently reference these routes—verify and update any docs or README to reflect both /api (Hono, Fastify, Elysia, Express) and /rpc/api (Next.js).

@jigz jigz mentioned this pull request Sep 6, 2025
@jigz

jigz commented Sep 7, 2025 •

Copy link
Copy Markdown

@dinwwwh

dinwwwh commented Sep 7, 2025

Copy link
Copy Markdown

@jigz
image
https://orpc.unnoq.com/docs/openapi/plugins/openapi-reference

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.

3 participants