Skip to content

Conversation

@fernando-yaeda
Copy link

@fernando-yaeda fernando-yaeda commented Dec 17, 2025

Summary

Adds an example demonstrating contract-first type-safe error handling in middlewares, as requested in #1282.

Changes

  • Defines errors in contracts
  • Implements authentication middleware using .errors() method

Summary by CodeRabbit

  • Bug Fixes

    • Endpoints now declare and return UNAUTHORIZED when a user is not authenticated.
  • Chores

    • Authentication logic centralized into a reusable middleware and applied to protected procedures.
  • Refactor

    • Simplified authentication wiring and handler signatures for protected routes.
  • Documentation

    • Added "Protected Procedures" guide and updated docs navigation explaining auth errors and middleware.

✏️ Tip: You can customize this high-level summary in your review settings.

@dosubot dosubot bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Dec 17, 2025
@coderabbitai
Copy link

coderabbitai bot commented Dec 17, 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 UNAUTHORIZED error specs to protected routes, introduces an AuthContext and authMiddleware that enforces those errors, rewires ORPC to use the middleware for authenticated routes, updates a handler signature, and adds documentation + a navigation entry for protected procedures.

Changes

Cohort / File(s) Summary
Contract error declarations
playgrounds/contract-first/src/contract/auth.ts, playgrounds/contract-first/src/contract/planet.ts
Added UNAUTHORIZED error spec (message: "User is not authenticated") to routes: me, createPlanet, updatePlanet. No input/output schema changes.
Authentication middleware
playgrounds/contract-first/src/middlewares/auth.ts
New AuthContext interface and exported authMiddleware that narrows contract errors, ensures context.user exists, and throws the contract UNAUTHORIZED error when absent.
Core ORPC configuration
playgrounds/contract-first/src/orpc.ts
Removed inline user/schema checks and ORPCContext; authed now uses pub.use(authMiddleware) and imports authMiddleware.
Auth router handler
playgrounds/contract-first/src/routers/auth.ts
me handler signature changed from handler(async ({ input, context }) to handler(async ({ context }) (unused input removed).
Docs & nav
apps/content/docs/contract-first/protected-procedures.md, apps/content/.vitepress/config.ts
Added documentation page for protected procedures and a "Protected Procedures" nav item under Contract First.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ORPC as ORPC Server
    participant AuthMW as authMiddleware
    participant Handler as Route Handler
    participant Contract as Contract Errors

    Client->>ORPC: call protected procedure
    ORPC->>AuthMW: invoke middleware with context
    AuthMW->>Contract: verify UNAUTHORIZED declared (type-narrow)
    alt context.user missing
        AuthMW->>Contract: throw UNAUTHORIZED
        Contract-->>Client: UNAUTHORIZED error
    else context.user present
        AuthMW->>Handler: forward call with enriched context
        Handler-->>Client: handler response
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review playgrounds/contract-first/src/middlewares/auth.ts for correct type-narrowing and thrown error shape.
  • Confirm all protected routes declare UNAUTHORIZED (auth.ts, planet.ts).
  • Verify authed composition in orpc.ts preserves middleware ordering and types.
  • Check me handler signature change in routers/auth.ts for callers/usage.

Possibly related PRs

  • unnoq/orpc#800 — Similar additions around authentication middleware and UNAUTHORIZED error declarations.
  • unnoq/orpc#248 — Changes touching the same contract-first playground auth/planet files and middleware wiring.

Poem

🐰 Hopping through contracts with glee,
I guard the gate where users be,
"User is not authenticated" I say,
Middleware hops and clears the way,
Docs tucked in — procedures safe today.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main objective: adding documentation for type-safe error handling in middleware. The changes demonstrate this through contract error definitions, middleware implementation using .errors(), and comprehensive documentation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 47acaa1 and f4a0358.

📒 Files selected for processing (1)
  • apps/content/docs/contract-first/protected-procedures.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/content/docs/contract-first/protected-procedures.md

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.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @fernando-yaeda, 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 introduces a robust example of type-safe error handling within middleware, specifically for authentication. It demonstrates how to define errors directly within API contracts and then utilize these definitions in a dedicated authentication middleware. This approach enhances type safety and consistency in error responses across the application, making the API more predictable and easier to consume, addressing the request in #1282.

Highlights

  • Error Definition in Contracts: The UNAUTHORIZED error has been explicitly defined within the me endpoint in auth.ts and the createPlanet and updatePlanet endpoints in planet.ts using the .errors() method, enabling type-safe error handling.
  • New Authentication Middleware: A new auth.ts middleware has been introduced to centralize authentication logic. This middleware leverages the contract-defined UNAUTHORIZED error for type-safe error handling, including a type narrowing check for error constructor access.
  • Middleware Refactoring: The orpc.ts file has been updated to integrate the new authMiddleware, simplifying the authed procedure chain and removing the previous inline authentication logic, leading to cleaner and more modular code.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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.

Copy link
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 a valuable example of type-safe error handling in middleware. The implementation is generally well-done, but I have a couple of suggestions to improve robustness and maintainability. The new authentication middleware currently throws a generic Error if a procedure's contract is missing the UNAUTHORIZED error, leading to a 500 Internal Server Error. I've proposed a more robust fallback that sends a proper UNAUTHORIZED response to the client. Additionally, I've noticed the UNAUTHORIZED error definition is duplicated across several files and suggest extracting it into a shared constant to improve code reuse and maintainability.

@fernando-yaeda fernando-yaeda marked this pull request as draft December 17, 2025 21:38
@fernando-yaeda fernando-yaeda marked this pull request as ready for review December 17, 2025 21:39
@unnoq
Copy link
Member

unnoq commented Dec 18, 2025

What about add and explain more detail on a vitpres doc page?

@fernando-yaeda
Copy link
Author

What about add and explain more detail on a vitpres doc page?

Will do. Working on in right now.

Also, could you share your thoughts on gemini suggestions? I'm not sure if they apply on playgrounds.

@unnoq
Copy link
Member

unnoq commented Dec 19, 2025

Also, could you share your thoughts on gemini suggestions? I'm not sure if they apply on playgrounds.

I don't think you should follow it

@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 Dec 19, 2025
Copy link

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

🧹 Nitpick comments (1)
apps/content/docs/contract-first/protected-procedures.md (1)

41-61: Consider adding import statement for clarity

The code example references implement without showing where it's imported from. While this keeps the example concise, beginners might benefit from seeing the complete import.

🔎 Optional addition

Consider adding an import statement at the beginning of the code block:

import { implement } from '@orpc/server'

export const authMiddleware = implement(contract)
  .$context<{ user?: { id: string, email: string } }>()
  .middleware(({ context, next, errors }) => {
    // ... rest of the code
  })
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a0a8197 and 2fcee11.

📒 Files selected for processing (2)
  • apps/content/.vitepress/config.ts (1 hunks)
  • apps/content/docs/contract-first/protected-procedures.md (1 hunks)
🔇 Additional comments (4)
apps/content/.vitepress/config.ts (1)

110-110: LGTM!

The navigation entry is properly placed within the "Contract First" section and follows the correct format.

apps/content/docs/contract-first/protected-procedures.md (3)

10-35: LGTM!

The section clearly demonstrates how to define errors in contracts using the .errors() method. The code example is well-structured and uses TypeScript twoslash for type checking.


63-77: LGTM!

The section effectively demonstrates the pattern of composing implementers using pub.use(authMiddleware). The info box helpfully clarifies the middleware inheritance behavior.


79-96: LGTM!

The examples clearly demonstrate the difference between public and protected procedures. The comment highlighting that context.user is guaranteed to exist in protected handlers is particularly helpful for understanding the benefit of this pattern.

fernando-yaeda and others added 2 commits December 19, 2025 12:09
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@@ -0,0 +1,96 @@
---
title: Protected Procedures
Copy link
Member

@unnoq unnoq Dec 20, 2025

Choose a reason for hiding this comment

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

I want to clarify that type-safe errors are an optional pattern, not a requirement. Because of that, I don’t think the “Protected Procedure” title is suitable here, or alternatively, the content is missing the approach for handling a normal ORPCError.

I think we should roll back the changes made in the playground and only mention type-safe errors as an optional approach, rather than treating them as the default.

Copy link
Author

Choose a reason for hiding this comment

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

It makes sense.

Should I proceed with reverting the playground changes and focus on the documentation changes by adding the normal ORPCError approach as a default and adding the type-safe errors as an option?

@codecov
Copy link

codecov bot commented Dec 21, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 21, 2025

More templates

@orpc/ai-sdk

npm i https://pkg.pr.new/@orpc/ai-sdk@1306

@orpc/arktype

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

@orpc/client

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

@orpc/contract

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

@orpc/experimental-durable-iterator

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

@orpc/hey-api

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

@orpc/interop

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

@orpc/json-schema

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

@orpc/nest

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

@orpc/openapi

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

@orpc/openapi-client

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

@orpc/otel

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

@orpc/experimental-pino

npm i https://pkg.pr.new/@orpc/experimental-pino@1306

@orpc/experimental-publisher

npm i https://pkg.pr.new/@orpc/experimental-publisher@1306

@orpc/experimental-publisher-durable-object

npm i https://pkg.pr.new/@orpc/experimental-publisher-durable-object@1306

@orpc/experimental-ratelimit

npm i https://pkg.pr.new/@orpc/experimental-ratelimit@1306

@orpc/react

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

@orpc/react-query

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

@orpc/experimental-react-swr

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

@orpc/server

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

@orpc/shared

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

@orpc/solid-query

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

@orpc/standard-server

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

@orpc/standard-server-aws-lambda

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

@orpc/standard-server-fastify

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

@orpc/standard-server-fetch

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

@orpc/standard-server-node

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

@orpc/standard-server-peer

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

@orpc/svelte-query

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

@orpc/tanstack-query

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

@orpc/trpc

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

@orpc/valibot

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

@orpc/vue-colada

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

@orpc/vue-query

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

@orpc/zod

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

commit: f4a0358

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.

2 participants