Repository navigation
feat(cli): add openapi suppport in orpc - #563
Conversation
WalkthroughAdds OpenAPI support for ORPC across CLI templates and helpers, updates dependency map to include Changes
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
✨ Finishing Touches🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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
authisn’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.urlfor/rpcvs/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 toapiHandleras well.If supported by
OpenAPIHandlerplugins 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
CORSPluginisn’t accepted byOpenAPIHandler, consider a tiny wrapper that sets CORS headers onreswhenapiHandlermatches.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 checkresponse. If the fetch adapter guaranteesresponseonly when matched, it’s fine. Otherwise, prefer amatchedgate 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.responsegating as above.- Optional: short-circuit by checking
req.nextUrl.pathname.startsWith('/rpc/api')before invokingapiHandlerto 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.
📒 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.tsapps/cli/src/constants.tsapps/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
UseBun.serve()for HTTP/WebSockets; do not useexpress
Usebun:sqlitefor SQLite; do not usebetter-sqlite3
UseBun.redisfor Redis; do not useioredis
UseBun.sqlfor Postgres; do not usepgorpostgres.js
Use built-inWebSocket; do not usews
PreferBun.fileovernode:fsreadFile/writeFile
UseBun.$instead ofexecafor shelling out
Files:
apps/cli/src/helpers/core/api-setup.tsapps/cli/src/constants.tsapps/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.tsapps/cli/src/constants.tsapps/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.
There was a problem hiding this comment.
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",createContextisn’t imported but is still called — this will break generation.- Uncaught errors in the raw
createServerhandler 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
interceptorsonce 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 theResponsepreserves 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
onErrorinterceptor 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.
📒 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/RPCHandlerwithfetchvariants andonError.
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
onErrorand 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 importZodToJsonSchemaConverterfrom@orpc/zod/zod4, and@orpc/zodis pinned to^1.8.6in your constants. Confirm that the generatedpackage.jsonalso declares a matchingzodv4.x dependency to avoid mismatched major versions.apps/cli/templates/backend/server/hono/src/index.ts.hbs (1)
95-96: Confirm docs include both/apiand/rpc/api. Post-install already prints
- OpenAPI (Scalar UI): http://localhost:3000/rpc/api for Next.js (orpc+next)
- OpenAPI (Scalar UI): http://localhost:3000/api for other backends
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).
|
does OpenAPIHandler create a path for api-reference as raw json/yaml? |


Summary by CodeRabbit
New Features
Documentation
Chores