●TOOLING — Rork's developer repos keep moving: rork-xcode was updated on July 16, rork-device on July 15, and rork-plist on July 13●OPUS46 — Claude Opus 4.6 is live in Rork, and Rork Max is built to assemble apps on top of Claude Code●SIM — A cloud iOS simulator runs in the browser, with one click to install on a device and two clicks to publish to the App Store●MAX — Rork Max emits pure Swift rather than React Native, reaching iPhone, iPad, Apple Watch, Apple TV, Vision Pro, and even iMessage●NATIVE — That opens up HealthKit, ARKit and LiDAR, NFC, Dynamic Island, Live Activities, 3D through Metal, and on-device inference with Core ML●SEED — Rork raised a $15M seed led by Left Lane Capital, with Peak XV and a16z Speedrun joining the round●TOOLING — Rork's developer repos keep moving: rork-xcode was updated on July 16, rork-device on July 15, and rork-plist on July 13●OPUS46 — Claude Opus 4.6 is live in Rork, and Rork Max is built to assemble apps on top of Claude Code●SIM — A cloud iOS simulator runs in the browser, with one click to install on a device and two clicks to publish to the App Store●MAX — Rork Max emits pure Swift rather than React Native, reaching iPhone, iPad, Apple Watch, Apple TV, Vision Pro, and even iMessage●NATIVE — That opens up HealthKit, ARKit and LiDAR, NFC, Dynamic Island, Live Activities, 3D through Metal, and on-device inference with Core ML●SEED — Rork raised a $15M seed led by Left Lane Capital, with Peak XV and a16z Speedrun joining the round
Rork Max × tRPC × Cloudflare Workers: Designing, Implementing, and Running a Type-Safe Edge API Backend
Build a type-safe edge API for Rork Max with tRPC and Cloudflare Workers. Covers project setup, Zod validation, JWT auth, KV caching, and CI/CD deployment.
Setup and context: The Hidden Cost of Untyped APIs in Mobile Development
When you're building a Rork Max app and connecting it to a backend API, a subtle but serious risk lurks beneath the surface: type divergence. The backend evolves, a field gets renamed, a response shape changes — and your mobile app continues calling the old API until a user reports a crash. By then, the damage is done.
This problem isn't unique to beginners. Even experienced TypeScript developers working on REST APIs routinely deal with the friction of manually keeping frontend and backend types in sync. You write an interface on the client, a matching type or schema on the server, and then spend mental energy ensuring they stay aligned. Code generation tools like OpenAPI Codegen or GraphQL Code Generator help, but they introduce their own complexity: schema files, generation scripts, versioning challenges.
tRPC (TypeScript Remote Procedure Call) takes a fundamentally different approach. Instead of generating types from a schema, it shares the type definitions themselves between your server and client. When you define a procedure on the server, your React Native components automatically know its input and output types — no generation step, no schema file, no manual sync. If the server type changes, your client shows a compile-time error immediately.
Pair this with Cloudflare Workers, and you have a globally distributed, low-latency backend that costs virtually nothing for indie app scales and scales seamlessly as your user base grows. This guide covers everything: project architecture, router design, authentication, caching, advanced middleware patterns, and a full CI/CD pipeline with GitHub Actions. It's written for developers comfortable with TypeScript who have shipped apps with Rork Max.
Understanding tRPC's Core Concepts
Procedures: The Building Blocks
In tRPC, everything revolves around procedures — server-side functions that your client calls directly. There are three types. A query is for reading data (equivalent to an HTTP GET). A mutation is for writing data (equivalent to a POST, PUT, or DELETE). A subscription is for real-time data streams over WebSocket, though we won't cover subscriptions in this guide since Cloudflare Workers has limited WebSocket support.
What makes procedures special is that they're defined with full TypeScript types, and those types are exported as a single AppRouter type that your client imports. No REST specification. No GraphQL schema. Just TypeScript.
Zod: Your First Line of Defense
tRPC uses Zod for input validation. Every procedure that accepts arguments must define a Zod schema for its input. This gives you two things at once: compile-time type safety (TypeScript infers types from Zod schemas) and runtime validation (malformed requests are rejected before they reach your business logic). For a mobile app where you control both client and server, you might wonder if runtime validation is really necessary. It is — because your API will eventually be called by users with older app versions, or potentially by third-party clients, and Zod protects you in all those cases.
The Router as a Contract
An appRouter in tRPC is essentially a typed API contract. When you export type AppRouter = typeof appRouter, you're exporting a structural description of every endpoint your backend exposes — its name, its input schema, and its output type. Your mobile app imports only this type (not any runtime code), which means you can keep your backend package out of your mobile bundle entirely.
✦
Thank you for reading this far.
Continue Reading
What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.
WHAT YOU'LL LEARN
✦Learn how to achieve complete type safety between your mobile app and server using tRPC + Cloudflare Workers, reducing runtime errors to near zero
✦Understand production-grade API design patterns including Zod validation, middleware architecture, and robust error handling
✦Master the full workflow from GitHub Actions × Wrangler CI/CD pipeline automation to edge deployment
Secure payment via Stripe · Cancel anytime
✦
Unlock This Article
Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.
Cloudflare Workers doesn't run your code in a single data center. It deploys your code to Cloudflare's network of 300+ data centers worldwide and executes each request at the location closest to the user making it. This is fundamentally different from traditional serverless functions like AWS Lambda, where your function runs in one region and adds latency for users elsewhere.
For a Rork Max app targeting a global audience, this difference is significant. A user in Tokyo calling your API doesn't need to wait for a round trip to a data center in US-East. Their request hits a Cloudflare data center in or near Japan and gets a response in milliseconds. This is what "edge computing" means in practice.
No Cold Starts
AWS Lambda and Google Cloud Functions suffer from cold starts: the first request after a period of inactivity can take several hundred milliseconds to a few seconds while the runtime initializes. Cloudflare Workers doesn't have this problem because it uses V8 isolates rather than full VMs or containers. Your code is always warm. For a mobile app where users expect instant feedback, eliminating cold starts noticeably improves the experience.
The Economics for Indie Developers
Cloudflare Workers' free tier is genuinely generous: 100,000 requests per day, 10ms CPU time per request, and access to KV storage with 100,000 reads and 1,000 writes per day. For most apps at the indie stage, this is enough to run indefinitely without paying anything. The paid Workers Paid plan is $5/month and adds 10 million requests per month and 30ms CPU time — enough to handle a modestly successful app with tens of thousands of daily active users.
Compare this to running even the smallest EC2 instance or a managed Postgres database, and the cost difference is stark. This stack lets you launch a production-quality backend for free and only start paying when you have meaningful revenue to justify it.
Environment Setup and Project Architecture
Choosing a Monorepo Structure
The key to making tRPC work is sharing the AppRouter type between packages. The cleanest way to achieve this in a Rork Max project is a monorepo managed with pnpm workspaces. You have your mobile app in apps/mobile and your API in packages/api. The mobile app imports only the TypeScript type from the API package — no runtime code crosses the boundary.
The jose library handles JWT signing and verification in Workers (native browser crypto API). We use Hono as a lightweight wrapper around the Workers fetch handler because it makes CORS configuration, logging, and route grouping much cleaner than raw Workers code.
The nodejs_compat flag is essential — tRPC and jose rely on Node.js built-ins like crypto that aren't available in the default Workers runtime. This flag adds compatibility polyfills for those modules.
Building the tRPC Router Layer
Initializing tRPC and Defining Context
Context is what makes tRPC procedures aware of their environment. Your context contains the Cloudflare environment bindings (D1 database, KV namespace, secrets) and any per-request data like the authenticated user ID. You define it once and every procedure has access to it through the ctx parameter.
// packages/api/src/trpc.tsimport { initTRPC, TRPCError } from '@trpc/server';import { z } from 'zod';export interface Context { env: Env; userId?: string;}const t = initTRPC.context<Context>().create({ errorFormatter({ shape, error }) { return { ...shape, data: { ...shape.data, zodError: error.cause instanceof z.ZodError ? error.cause.flatten() : null, }, }; },});export const router = t.router;// Open to everyoneexport const publicProcedure = t.procedure;// Requires a valid JWT — throws UNAUTHORIZED otherwiseexport const protectedProcedure = t.procedure.use(({ ctx, next }) => { if (!ctx.userId) { throw new TRPCError({ code: 'UNAUTHORIZED', message: 'Authentication required', }); } return next({ ctx: { ...ctx, userId: ctx.userId } });});
The errorFormatter ensures that Zod validation errors are surfaced to the client in a structured, queryable format. When input validation fails, the client receives error.data.zodError.fieldErrors — an object mapping each invalid field to its error messages. This lets your Rork Max form components show precise, field-level errors without any additional error parsing logic.
Root Router Composition
Organizing your router by domain keeps each file focused and testable. The root router simply composes them:
// packages/api/src/router/index.tsimport { router } from '../trpc';import { authRouter } from './auth';import { userRouter } from './user';import { contentRouter } from './content';export const appRouter = router({ auth: authRouter, user: userRouter, content: contentRouter,});export type AppRouter = typeof appRouter;
A Well-Designed User Router
Here's a user router that demonstrates the full range of tRPC patterns: schema definition with Zod, output type contracts, database queries via D1, and proper error handling:
// packages/api/src/router/user.tsimport { z } from 'zod';import { router, protectedProcedure, publicProcedure } from '../trpc';import { TRPCError } from '@trpc/server';const UserSchema = z.object({ id: z.string().uuid(), name: z.string().min(1).max(50), email: z.string().email(), bio: z.string().max(200).optional(), avatarUrl: z.string().url().optional(), createdAt: z.string(),});export const userRouter = router({ getProfile: publicProcedure .input(z.object({ userId: z.string().uuid() })) .output(UserSchema) .query(async ({ input, ctx }) => { const result = await ctx.env.DB.prepare( 'SELECT * FROM users WHERE id = ?' ).bind(input.userId).first(); if (!result) { throw new TRPCError({ code: 'NOT_FOUND', message: 'User not found', }); } return result as z.infer<typeof UserSchema>; }), updateProfile: protectedProcedure .input(z.object({ name: z.string().min(1).max(50).optional(), bio: z.string().max(200).optional(), })) .mutation(async ({ input, ctx }) => { const updates: string[] = []; const values: unknown[] = []; if (input.name) { updates.push('name = ?'); values.push(input.name); } if (input.bio !== undefined) { updates.push('bio = ?'); values.push(input.bio); } if (updates.length === 0) { throw new TRPCError({ code: 'BAD_REQUEST', message: 'No fields to update' }); } values.push(new Date().toISOString(), ctx.userId); await ctx.env.DB.prepare( `UPDATE users SET ${updates.join(', ')}, updated_at = ? WHERE id = ?` ).bind(...values).run(); return { success: true }; }),});
Defining both .input() and .output() on a procedure is a useful discipline for premium APIs. The output schema acts as a contract: if your database query returns a shape that doesn't match UserSchema, you'll get a runtime error in development before it reaches production.
The Cloudflare Workers Entry Point
Hono + tRPC Integration
Hono is a lightweight web framework for Cloudflare Workers. Its @hono/trpc-server package provides a middleware that bridges tRPC and Hono's request handling. The combination is cleaner than writing raw Workers fetch handlers because Hono gives you composable middleware for CORS, logging, and route grouping.
// packages/api/src/index.tsimport { Hono } from 'hono';import { cors } from 'hono/cors';import { logger } from 'hono/logger';import { trpcServer } from '@hono/trpc-server';import { appRouter } from './router';import { createContext } from './context';export interface Env { DB: D1Database; CACHE: KVNamespace; JWT_SECRET: string; ENVIRONMENT: string;}const app = new Hono<{ Bindings: Env }>();app.use('/trpc/*', cors({ origin: ['https://your-rork-app.com', 'exp://localhost:8081'], allowMethods: ['GET', 'POST', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization'], credentials: true,}));app.use('/trpc/*', logger());app.use('/trpc/*', trpcServer({ router: appRouter, createContext: async (opts, c) => createContext(opts, c),}));app.get('/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }));export default app;
JWT Authentication in Context
The context creation function runs on every request and is where you extract and verify the JWT token. The important design choice here is that an invalid or missing token doesn't throw — it simply leaves userId as undefined. Protected procedures will then reject unauthorized requests. This allows a single entry point to serve both public and protected procedures without route-level auth guards.
// packages/api/src/context.tsimport { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch';import type { Context } from 'hono';import type { Env } from './index';import * as jose from 'jose';export async function createContext( opts: FetchCreateContextFnOptions, c: Context<{ Bindings: Env }>) { const authHeader = opts.req.headers.get('Authorization'); let userId: string | undefined; if (authHeader?.startsWith('Bearer ')) { const token = authHeader.slice(7); try { const secret = new TextEncoder().encode(c.env.JWT_SECRET); const { payload } = await jose.jwtVerify(token, secret); userId = payload.sub as string; } catch { // Invalid or expired token — proceed as unauthenticated } } return { env: c.env, userId };}
Building the Rork Max Client
Initializing the tRPC Client
The crucial step here is importing AppRouter as a type-only import. This ensures no backend code ends up in your mobile bundle — you're importing only the TypeScript shape, which the compiler strips entirely at build time.
The httpBatchLink automatically batches multiple tRPC calls that happen in the same render cycle into a single HTTP request. This is a significant performance win for screens that need to fetch several pieces of data simultaneously — instead of three separate round trips, you make one.
Setting Up React Query Provider
tRPC uses React Query under the hood for caching, refetching, and loading state management. You need to provide both a QueryClient and the trpc provider:
Notice that you never had to define types for profile. TypeScript infers them directly from your server-side UserSchema via AppRouter. If you add a field to the user profile on the server, it immediately appears as a typed property here. If you remove a field, any client code accessing that field becomes a compile error.
Advanced Production Patterns
Database Schema and Migrations with D1
Cloudflare D1 is a SQLite-compatible database that runs at the edge alongside your Workers code. Define your schema in SQL migration files and manage them with Wrangler:
-- packages/api/src/db/migrations/0001_create_users.sqlCREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY DEFAULT (lower(hex(randomblob(16)))), name TEXT NOT NULL, email TEXT UNIQUE NOT NULL, bio TEXT, avatar_url TEXT, created_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')));CREATE INDEX idx_users_email ON users(email);
# Create and apply migrationsnpx wrangler d1 create my-rork-dbnpx wrangler d1 migrations apply my-rork-db --local # Local devnpx wrangler d1 migrations apply my-rork-db # Production
D1 queries are simple: prepare a parameterized statement with .prepare(), bind values with .bind(), and execute with .first() (one row), .all() (all rows), or .run() (mutations).
KV Caching for High-Read Data
Not every piece of data needs to hit the database on every request. Featured content, configuration, and computed aggregates are good candidates for KV caching. A simple wrapper function makes the pattern reusable:
// packages/api/src/utils/cache.tsexport async function withCache<T>( kv: KVNamespace, key: string, ttlSeconds: number, fetcher: () => Promise<T>): Promise<T> { const cached = await kv.get(key, 'json'); if (cached !== null) return cached as T; const fresh = await fetcher(); await kv.put(key, JSON.stringify(fresh), { expirationTtl: ttlSeconds }); return fresh;}// In a router — transparent caching of expensive queriesexport const contentRouter = router({ getFeaturedContent: publicProcedure.query(async ({ ctx }) => { return withCache(ctx.env.CACHE, 'featured-content', 300, async () => ctx.env.DB.prepare( 'SELECT * FROM content WHERE featured = 1 ORDER BY created_at DESC LIMIT 10' ).all() ); }),});
Five-minute caching of featured content means the database is queried at most twelve times per hour for that data, regardless of how many users hit the endpoint simultaneously.
Middleware for Rate Limiting
For procedures that could be abused — like authentication endpoints or content generation — add rate limiting via tRPC middleware:
// packages/api/src/middleware/rateLimit.tsimport { TRPCError } from '@trpc/server';import { t } from '../trpc';export const rateLimitMiddleware = t.middleware(async ({ ctx, next, path }) => { const ip = 'client-ip'; // In practice, read from CF-Connecting-IP header const key = `rate-limit:${ip}:${path}`; const limit = 60; const current = await ctx.env.CACHE.get(key); const count = current ? parseInt(current) : 0; if (count >= limit) { throw new TRPCError({ code: 'TOO_MANY_REQUESTS', message: 'Rate limit exceeded. Please try again in a minute.', }); } await ctx.env.CACHE.put(key, String(count + 1), { expirationTtl: 60 }); return next();});// Apply to a procedureexport const rateLimitedProcedure = publicProcedure.use(rateLimitMiddleware);
tRPC middleware composes cleanly. You can combine rate limiting, authentication, and logging into a single procedure type by chaining .use() calls.
Troubleshooting Common Issues
CORS Errors in Expo Development
When running your Rork Max app in Expo Go or the Expo development server, requests originate from exp://localhost:8081 or a local network IP. Make sure your Hono CORS configuration explicitly allows these origins. In production Expo builds (standalone apps), requests come from the device's network stack without an Origin header, so you may not see CORS issues at all — but it's worth testing with a standalone build before assuming the configuration is correct.
Workers Fails to Start with nodejs_compat
If you see errors about missing Node.js modules like crypto or buffer, ensure compatibility_flags = ["nodejs_compat"] is present in your wrangler.toml. Without it, any npm package that internally uses Node.js built-ins will fail at startup.
Type Inference Broken After Adding a New Procedure
The most common cause is a circular import. If your new router file imports from a file that (directly or indirectly) imports from the router itself, TypeScript's type inference can break. Keep your router files import-clean: routers import from ../trpc and utility modules, never from other routers or the root index.ts.
D1 Query Returns Unexpected Column Names
Cloudflare D1 returns column names exactly as they appear in the database schema. If your schema uses avatar_url (snake_case) but your TypeScript type expects avatarUrl (camelCase), the Zod parse will fail. Either normalize column names in SQL using AS aliases (SELECT avatar_url AS avatarUrl FROM users) or transform the result in the query handler before returning.
CI/CD Pipeline with GitHub Actions
Automating deployment removes the risk of forgetting a step, ensures migrations always run before new code deploys, and gives you a deployment audit trail through GitHub Actions history.
Add CLOUDFLARE_API_TOKEN (generated from the Cloudflare dashboard under API Tokens with Workers and D1 permissions) and CLOUDFLARE_ACCOUNT_ID to your repository's Secrets. From that point on, every merge to main that touches the API package automatically runs type checks, applies migrations, and deploys to the global edge network.
For even more confidence, add a staging environment by creating a second wrangler.toml environment block and a separate GitHub Actions job that deploys to staging on pull requests, with production deployment gated on merge to main.
A Note from an Indie Developer
Key Takeaways
The Rork Max × tRPC × Cloudflare Workers stack represents one of the most compelling full-stack architectures available to indie mobile developers in 2026. End-to-end type safety means the most common class of API bugs — mismatched types, renamed fields, changed response shapes — are caught by the compiler before they ever reach users. Cloudflare Workers' global edge execution means your users get low-latency responses regardless of where they are. And the economics make it realistic to launch and run a production backend for free until your app achieves meaningful scale.
The learning curve is real, particularly around monorepo tooling and Cloudflare Workers' environment model. But once the foundation is in place, the development velocity that comes from complete end-to-end type safety is genuinely transformative. You spend less time writing interface files, less time debugging mismatched data shapes, and more time building features your users actually want.
Start with a single router and a few procedures. Add authentication. Then caching. Then CI/CD. Each layer builds naturally on the previous one. Within a week of following this guide, you'll have a globally distributed, type-safe API backend running in production — and a development workflow that makes you genuinely reluctant to build any other way.
Share
Thank You for Reading
Rork Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.