Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    A few thoughts on tRPC

    This week I tried a new stack for building webapps and found it pretty great. This isn't like a tutorial or anything, just a few thoughts and some code.

    What's the most annoying part of building a webapp? The server-client separation.

    Your application runs on different computers and now you have to deal with that split. Data and core business logic tends to live on the server. UI and light logic live on the client.

    To get them talking, you need an API layer. This is where shit hits the fan.

    Common types of APIs

    REST is the gold standard with well-known advantages and drawbacks. The biggest issue is that APIs tend to balloon in size and are often built for 1 specific use-case in 1 specific client.

    GraphQL made a good run at being the new gold standard, but never quite caught on. Great for complex reads, clunky for writes. Easy to write database-killing queries.

    RPC โ€“ remote procedure call โ€“ is more of a vibe than a technology. You call an API with a specific function/task in mind. Many if not most REST and GraphQL APIs that I've seen are secretly RPC in shape.

    You are almost guaranteed to build an RPC-shaped API, if you're building 1 specific server for 1 specific client. Sometimes RPC-over-REST is even the right choice! Like when a bunch of business logic needs to happen from a user action.

    What's tRPC

    tRPC is a ... framework? ... for building end-to-end type safe RPC APIs.

    That means you get full type support with autocomplete on the server and the client. And runtime validation that your inputs and outputs match your API spec ๐Ÿ˜

    Best part: Without manually specifying or copying types in a bunch of places. TypeScript infers almost everything.

    What's tRPC like to use

    Here's example code from a project I'm building for AI Summit. We're trying to match conference attendees based on interests and suggest they meet. Excited to see if this works ๐Ÿคž

    I rolled into an existing project and can't give you the full tutorial. Just the parts I know about โ€“ย adding an endpoint and calling it from React.

    Creating an endpoint

    To create endpoints you make a new tRPC router:

    export const matchingRouter = createTRPCRouter({});
    

    You define your endpoints as keys in that object. Each endpoint is a resolver function that gets an input and returns a response.

      getMatches: publicProcedure
        .input(z.string())
        .query(async ({ input, ctx }) => {
    			const matches = // read data from a database or whatever
    			// it's just TypeScript, you can do whatever
    
          return matches;
        }),
    

    Here I'm using zod to specify my input type and perform run-time validation. The tRPC + Zod integration is nice enough that VSCode knows that the input argument is a string ๐Ÿ˜

    You can specify complex shapes and VSCode flawlessly picks up on that.

    Fetching your endpoint

    To fetch your endpoints, you'll need a tRPC client. In this case optimized for Next.js.

    export const api = createTRPCNext<AppRouter>({
      config() {
        return {
          // ...
        };
      },
    
      ssr: false,
    });
    

    You then use queries same as you would with React Query. I think tRPC even uses React Query under the hood.

    api.matching.getMatches.useQuery("clnb896di0002c949ugw700yc", {
      onSuccess: (data) => {
        console.log("hai", data);
      },
    });
    

    tRPC gives you autocomplete for your API structure and the query ensures your component re-renders when new data becomes available. Does all the re-fetching and caching for you too.

    What does an API call look like?

    API calls are based on HTTP because we're on the web. No surprises here.

    It does look like tRPC batches your API calls to reduce network traffic. That's neat.

    Batched API call
    Batched API call
    API call response
    API call response

    Ideally you'd never care about any of this. tRPC hides the details and makes your code work.

    Good for writes?

    Yep! tRPC writes don't feel clunky at all.

    You define the router as .mutation instead of query and make calls with useMutation instead of query. Everything else works the same.

    tRPC good or bad?

    I liked it!

    Super productive to work with, easy to jump into. Not sure I'd use it for a large project with a deep backend or when you have a bunch of clients that need to read the same data but in different shapes.

    Feels like tRPC works best when you use the backend-for-frontend pattern. But I love that there's no fiddling with API definitions or any of that stuff.

    Cheers,
    ~Swizec

    Published on October 6th, 2023 in Fullstack, tRPC, NextJS, React Query, React

    Did you enjoy this article?

    Continue reading about A few thoughts on tRPC

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help ๐Ÿ‘‰ swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers ๐Ÿ‘‰ ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are โค๏ธ

    Created by Swizec with โค๏ธ