Convert Figma logo to code with AI

trpc logotrpc

🧙‍♀️ Move Fast and Break Nothing. End-to-end typesafe APIs made easy.

37,102
1,352
37,102
170

Top Related Projects

42,699

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

A reference implementation of GraphQL for JavaScript

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.

71,524

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

Blazing fast, instant realtime GraphQL APIs on all your data with fine grained access control, also trigger webhooks on database events.

42,942

C++ based gRPC (C++, Python, Ruby, Objective-C, PHP, C#)

Quick Overview

tRPC (TypeScript-RPC) is a framework for building type-safe APIs with TypeScript. It provides a simple and intuitive way to create and consume APIs, with a focus on type safety and developer experience. tRPC is designed to work seamlessly with popular web frameworks like React, Next.js, and Node.js.

Pros

  • Type Safety: tRPC ensures type safety throughout the entire API lifecycle, from the server to the client, reducing the risk of runtime errors.
  • Simplicity: tRPC has a straightforward and easy-to-use API, making it accessible for developers of all skill levels.
  • Flexibility: tRPC can be used with a variety of web frameworks and can be easily integrated into existing projects.
  • Scalability: tRPC's modular design allows for easy scaling and maintainability as the project grows.

Cons

  • Learning Curve: While tRPC is relatively simple to use, it may have a steeper learning curve for developers who are not familiar with TypeScript or the concept of type-safe APIs.
  • Dependency on TypeScript: tRPC is built on TypeScript, which may be a limitation for developers who prefer to work with JavaScript.
  • Limited Community: Compared to some other popular web frameworks, the tRPC community is relatively small, which may limit the availability of third-party plugins and resources.
  • Performance Overhead: The type-checking and validation performed by tRPC may introduce some performance overhead, especially for large or complex APIs.

Code Examples

Creating a tRPC Server

import { initTRPC } from '@trpc/server';

const t = initTRPC.create();

const appRouter = t.router({
  hello: t.procedure.query(() => 'world'),
});

export type AppRouter = typeof appRouter;

This code sets up a basic tRPC server with a single hello query that returns the string 'world'.

Consuming a tRPC API in a React Application

import { createTRPCClient } from '@trpc/client';
import { AppRouter } from './server';

const client = createTRPCClient<AppRouter>({
  url: 'http://localhost:3000/trpc',
});

async function App() {
  const hello = await client.query('hello');
  return <div>The server said: {hello}</div>;
}

This code creates a tRPC client that can be used to interact with the server-side API defined earlier. The client.query() method is used to call the hello query and display the result in a React component.

Defining a tRPC Procedure with Input and Output Types

import { z } from 'zod';

const appRouter = t.router({
  addNumbers: t.procedure
    .input(z.object({ a: z.number(), b: z.number() }))
    .output(z.number())
    .query((req) => req.input.a + req.input.b),
});

This code defines a tRPC procedure called addNumbers that takes two numbers as input and returns their sum. The input and output types are defined using the Zod library, ensuring type safety throughout the API.

Getting Started

To get started with tRPC, follow these steps:

  1. Install the required dependencies:
npm install @trpc/server @trpc/client zod
  1. Create a new tRPC server:
import { initTRPC } from '@trpc/server';

const t = initTRPC.create();

const appRouter = t.router({
  hello: t.procedure.query(() => 'world'),
});

export type AppRouter = typeof appRouter;
  1. Create a tRPC client to interact with the server:
import { createTRPCClient } from '@trpc/client';
import { AppRouter } from './server';

const client = createTRPCClient<AppRouter>({
  url: 'http://localhost:3000/trpc',
});

async function App() {
  const hello = await client.query('hello');
  return <div>The server said: {hello}</div>;
}

Competitor Comparisons

42,699

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB

Pros of Prisma

  • Provides a powerful ORM with type-safe database access
  • Offers database migrations and schema management
  • Supports multiple databases (PostgreSQL, MySQL, SQLite, etc.)

Cons of Prisma

  • Steeper learning curve for developers new to ORMs
  • Requires additional setup and configuration
  • May introduce performance overhead for complex queries

Code Comparison

Prisma:

const user = await prisma.user.create({
  data: { name: 'Alice', email: 'alice@example.com' },
});

tRPC:

const createUser = t.procedure
  .input(z.object({ name: z.string(), email: z.string().email() }))
  .mutation(async ({ input }) => {
    // Implementation to create user
  });

Key Differences

  • Prisma focuses on database operations and schema management, while tRPC is centered around type-safe API development
  • Prisma provides a database abstraction layer, whereas tRPC facilitates end-to-end typesafe APIs
  • tRPC is more lightweight and flexible, allowing integration with various data access methods

Use Cases

  • Choose Prisma for projects requiring robust database management and ORM capabilities
  • Opt for tRPC when building type-safe APIs with a focus on full-stack TypeScript development

A reference implementation of GraphQL for JavaScript

Pros of graphql-js

  • Widely adopted and battle-tested in production environments
  • Extensive ecosystem with numerous tools and libraries
  • Supports a schema-first approach, allowing for better API design and documentation

Cons of graphql-js

  • Steeper learning curve due to its complex type system and schema definition
  • Requires more boilerplate code for setup and query resolution
  • Can be overkill for smaller projects or simpler API needs

Code Comparison

graphql-js:

const schema = buildSchema(`
  type Query {
    hello: String
  }
`);

const root = {
  hello: () => 'Hello, world!',
};

tRPC:

export const appRouter = router({
  hello: publicProcedure
    .query(() => 'Hello, world!'),
});

The graphql-js example shows the schema definition and resolver setup, while the tRPC example demonstrates a simpler, code-first approach to defining an API endpoint. tRPC requires less boilerplate and offers type safety out of the box, making it easier to use for TypeScript projects. However, graphql-js provides more flexibility and a standardized query language that can be beneficial for larger, more complex APIs.

🌍  Spec-compliant and production ready JavaScript GraphQL server that lets you develop in a schema-first way. Built for Express, Connect, Hapi, Koa, and more.

Pros of Apollo Server

  • Widely adopted and battle-tested in production environments
  • Extensive ecosystem with tools like Apollo Client and Apollo Studio
  • Supports a wide range of data sources and integrations

Cons of Apollo Server

  • Steeper learning curve, especially for complex setups
  • Requires manual schema definition and resolver implementation
  • Potential performance overhead for simple use cases

Code Comparison

Apollo Server:

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

tRPC:

export const appRouter = router({
  hello: publicProcedure
    .query(() => {
      return 'Hello world!';
    }),
});

Key Differences

  • tRPC offers end-to-end type safety without the need for code generation
  • Apollo Server uses GraphQL, while tRPC uses RPC-style API calls
  • tRPC has a simpler setup process and smaller learning curve
  • Apollo Server provides more flexibility for complex data fetching scenarios
  • tRPC has better performance for simple APIs due to less overhead

Both projects have their strengths and are suitable for different use cases. Apollo Server excels in complex, large-scale applications with diverse data sources, while tRPC shines in TypeScript-based projects that prioritize simplicity and type safety.

71,524

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀

Pros of NestJS

  • Full-featured framework with built-in support for dependency injection, modules, and decorators
  • Extensive ecosystem with many official and community-driven packages
  • Strong TypeScript support and object-oriented programming principles

Cons of NestJS

  • Steeper learning curve due to its comprehensive nature and Angular-inspired architecture
  • Heavier and more opinionated, which may be overkill for smaller projects
  • Requires more boilerplate code compared to tRPC's minimal approach

Code Comparison

NestJS:

@Controller('users')
export class UsersController {
  @Get(':id')
  findOne(@Param('id') id: string) {
    return `This action returns a user with id ${id}`;
  }
}

tRPC:

export const appRouter = router({
  getUser: publicProcedure
    .input(z.string())
    .query((opts) => {
      return `This action returns a user with id ${opts.input}`;
    }),
});

NestJS provides a more structured, decorator-based approach, while tRPC offers a simpler, function-based API. NestJS is better suited for large, complex applications, whereas tRPC excels in smaller projects or those requiring seamless type safety between client and server.

Blazing fast, instant realtime GraphQL APIs on all your data with fine grained access control, also trigger webhooks on database events.

Pros of GraphQL Engine

  • Provides a ready-to-use GraphQL API with automatic CRUD operations
  • Offers real-time subscriptions out of the box
  • Includes a web-based console for easy schema management and API exploration

Cons of GraphQL Engine

  • Requires a separate database setup and management
  • Less flexible for custom business logic implementation
  • Steeper learning curve for developers new to GraphQL

Code Comparison

GraphQL Engine query:

query {
  users {
    id
    name
    email
  }
}

tRPC procedure call:

const result = await trpc.users.list.query();

Key Differences

  • GraphQL Engine generates a GraphQL API based on your database schema, while tRPC allows you to define type-safe procedures in TypeScript
  • GraphQL Engine provides a more comprehensive solution for database-backed APIs, whereas tRPC focuses on end-to-end typesafety for RPC-style communication
  • tRPC offers better integration with TypeScript projects and existing Node.js ecosystems, while GraphQL Engine is more suited for projects requiring a full-featured GraphQL API with minimal setup

Both projects have their strengths, and the choice between them depends on your specific project requirements, team expertise, and preferred development workflow.

42,942

C++ based gRPC (C++, Python, Ruby, Objective-C, PHP, C#)

Pros of gRPC

  • Highly efficient binary serialization with Protocol Buffers
  • Built-in support for streaming and bidirectional communication
  • Strong typing and code generation for multiple languages

Cons of gRPC

  • Steeper learning curve and more complex setup
  • Less browser-friendly, requiring additional tools for web clients
  • Heavier payload due to Protocol Buffers overhead for small messages

Code Comparison

gRPC (Protocol Buffers definition):

syntax = "proto3";

service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}

message HelloRequest {
  string name = 1;
}

message HelloReply {
  string message = 1;
}

tRPC (TypeScript definition):

import { z } from 'zod';
import { publicProcedure, router } from '../trpc';

export const appRouter = router({
  hello: publicProcedure
    .input(z.object({ name: z.string() }))
    .query(({ input }) => {
      return { greeting: `Hello ${input.name}!` };
    }),
});

Both gRPC and tRPC offer type-safe API development, but gRPC provides a more language-agnostic approach with Protocol Buffers, while tRPC leverages TypeScript's type system for a more JavaScript-centric experience.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

tRPC

tRPC

Move fast and break nothing.
End-to-end typesafe APIs made easy.

codecov weekly downloads MIT License Discord
Twitter

Demo

The client above is not importing any code from the server, only its type declarations.


Intro

tRPC allows you to easily build & consume fully typesafe APIs without schemas or code generation.

Features

  • ✅  Well-tested and production ready.
  • 🧙‍♂️  Full static typesafety & autocompletion on the client, for inputs, outputs, and errors.
  • 🐎  Snappy DX - No code generation, run-time bloat, or build pipeline.
  • 🍃  Light - tRPC has zero deps and a tiny client-side footprint.
  • 🐻  Easy to add to your existing brownfield project.
  • 🔋  Batteries included - React.js/Next.js/Express.js/Fastify adapters. (But tRPC is not tied to React, and there are many community adapters for other libraries)
  • 🥃  Subscriptions support.
  • ⚡️  Request batching - requests made at the same time can be automatically combined into one
  • 👀  Quite a few examples in the ./examples-folder

Quickstart

There are a few examples that you can use for playing out with tRPC or bootstrapping your new project. For example, if you want a Next.js app, you can use the full-stack Next.js example:

Quick start with a full-stack Next.js example:

# yarn
yarn create next-app --example https://github.com/trpc/trpc --example-path examples/next-prisma-starter trpc-prisma-starter

# npm
npx create-next-app --example https://github.com/trpc/trpc --example-path examples/next-prisma-starter trpc-prisma-starter

# pnpm
pnpm create next-app --example https://github.com/trpc/trpc --example-path examples/next-prisma-starter trpc-prisma-starter

# bun
bunx create-next-app --example https://github.com/trpc/trpc --example-path examples/next-prisma-starter trpc-prisma-starter

# deno
deno init --npm next-app --example https://github.com/trpc/trpc --example-path examples/next-prisma-starter trpc-prisma-starter

👉 See full documentation on tRPC.io. 👈

Star History

Star History Chart

Core Team

Do you want to contribute? First, read the Contributing Guidelines before opening an issue or PR so you understand the branching strategy and local development environment. If you need any more guidance or want to ask more questions, feel free to write to us on Discord!

Project leads

The people who lead the API-design decisions and have the most active role in the development


Alex / KATT

Julius Marminge

Nick Lucas

Active contributors

People who actively help out improving the codebase by making PRs and reviewing code


Hubert Mathieu

Special shout-outs

Individuals who have made exceptional contributions to tRPC through code, documentation, community building, and other valuable efforts


Theo Browne

Sachin Raja

Sponsors

If you enjoy working with tRPC and want to support us, consider giving a token appreciation by GitHub Sponsors!

🥈 Silver Sponsors

Cal.com,%20Inc.
Cal.com, Inc.
Greptile
Greptile
CodeRabbit
CodeRabbit

🥉 Bronze Sponsors

Dr.%20B
Dr. B
Ryan%20Magoon
Ryan Magoon
JonLuca%20De%20Caro
JonLuca De Caro

😻 Smaller Backers

Ahoy%20Labs
Ahoy Labs
Unkey
Unkey
Tom%20Ballinger
Tom Ballinger
Proxidize
Proxidize
rickk
rickk
Jaron%20Heard
Jaron Heard
Brooke%20Holmes
Brooke Holmes
Max%20Greenwald
Max Greenwald
Dmitry%20Maykov
Dmitry Maykov
Chris%20Bradley
Chris Bradley
Liminity%20AB
Liminity AB
Val%20Town
Val Town
Illarion%20Koperski
Illarion Koperski
Kalle
Kalle
Jared%20Wyce
Jared Wyce
fanvue
fanvue
Ascent%20Factory
Ascent Factory
Drew%20Powers
Drew Powers
Drizzle%20Team
Drizzle Team
Leo%20Jace
Leo Jace
Jonas%20Strassel
Jonas Strassel
Spencer%20McKenney
Spencer McKenney
Stefan%20Wallin
Stefan Wallin
Maicon%20Carraro
Maicon Carraro
Andrei%20Karushev
Andrei Karushev
Venue%20Ink
Venue Ink
BestKru
BestKru
Brian%20Curliss
Brian Curliss
Illarion%20Koperski
Illarion Koperski

All contributors ✨

A table of avatars from the project's contributors


Powered by Vercel

NPM DownloadsLast 30 Days