Al
Alex Johansson & tRPC Community@KATTCore Maintainer VerifiedtRPC

Specification Author & Maintainer • Verified via AgentRules Industrial Quality Gate

backendhigh PriorityID: trpc-v11-typesafe

tRPC v11 End-to-End Type Safety & Procedure Standard

Conventions for tRPC v11: modular sub-routers, superjson transformer for dates/maps, middleware authorization guards, and input/output schema validation.

Prohibited Anti-Pattern: AI uses untyped procedures, bypasses middleware for authentication, or forgets superjson.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: tRPC v11 End-to-End Type Safety & Procedure Standard - Conventions for tRPC v11: modular sub-routers, superjson transformer for dates/maps, middleware authorization guards, and input/output schema validation.
globs: src/server/routers/**/*.ts, src/trpc/**/*.ts
alwaysApply: false
author: "Alex Johansson & tRPC Community (@KATT)"
contributor_url: "https://github.com/KATT"
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/trpc-v11-typesafe"
---

# tRPC v11 End-to-End Type Safety & Procedure Standard

> **Severity**: HIGH | **Category**: backend
> **Anti-Pattern Warning**: AI uses untyped procedures, bypasses middleware for authentication, or forgets superjson.

## System Constraints
You are a full-stack TypeScript engineer using tRPC v11. Always define publicProcedure and protectedProcedure with reusable middlewares. Validate all inputs with Zod. Use superjson transformer to serialize Dates and BigInts without manual string conversion.

## Strict Guidelines
- Split root router into focused sub-routers (userRouter, postRouter).
- Protect sensitive procedures using reusable auth middleware: protectedProcedure = t.procedure.use(isAuthed).
- Always validate procedure input with .input(z.object({...})).

## Bad vs Good Implementations
### Protected Procedure with Zod Input Validation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Allows unauthenticated users to mutate records with arbitrary unvalidated input.
```typescript
// Anti-pattern: Missing authentication guard and input validation
export const userRouter = router({
  updateBio: publicProcedure.mutation(async ({ input, ctx }: any) => {
    // Anyone can update any user's bio!
    return ctx.db.user.update({ where: { id: input.userId }, data: { bio: input.bio } });
  }),
});
```

#### Production Standard (Correct)
> **Standard**: Guarantees valid session context and strictly typed, sanitized inputs.
```typescript
// Production Standard: Protected procedure with Zod input validation
import { z } from "zod";
import { router, protectedProcedure } from "../trpc";

export const userRouter = router({
  updateBio: protectedProcedure
    .input(z.object({ bio: z.string().max(500) }))
    .mutation(async ({ input, ctx }) => {
      return ctx.db.user.update({
        where: { id: ctx.session.user.id },
        data: { bio: input.bio },
      });
    }),
});
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: tRPC v11 End-to-End Type Safety & Procedure Standard

tRPC v11 End-to-End Type Safety & Procedure Standard defines an industrial-grade behavioral standard for backend engineering. Conventions for tRPC v11: modular sub-routers, superjson transformer for dates/maps, middleware authorization guards, and input/output schema validation. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI uses untyped procedures, bypasses middleware for authentication, or forgets superjson. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI uses untyped procedures, bypasses middleware for authentication, or forgets superjson.High
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Split root router into focused sub-routers (userRouter, postRouter).

Split root router into focused sub-routers (userRouter, postRouter).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Protect sensitive procedures using reusable auth middleware

Protect sensitive procedures using reusable auth middleware: protectedProcedure = t.procedure.use(isAuthed).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Always validate procedure input with .input(z.object({...})).

Always validate procedure input with .input(z.object({...})).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is tRPC v11 End-to-End Type Safety & Procedure Standard critical for AI coding assistants?

Conventions for tRPC v11: modular sub-routers, superjson transformer for dates/maps, middleware authorization guards, and input/output schema validation. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI uses untyped procedures, bypasses middleware for authentication, or forgets superjson.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

tRPC