tRPC + NextJS App Router = Simple Typesafe APIs

แชร์
ฝัง
  • เผยแพร่เมื่อ 8 พ.ย. 2024

ความคิดเห็น • 378

  • @olivercordingley6588
    @olivercordingley6588 7 หลายเดือนก่อน +15

    This has got to be the 30th time I've watched this video over a 7 month period. Legendary.

    • @jherr
      @jherr  7 หลายเดือนก่อน +1

      Thank you!

    • @lemonz445
      @lemonz445 7 หลายเดือนก่อน +1

      Same, it's so good! Thanks for all the work here Jack, you're making us all better.

    • @RobertSeghedi
      @RobertSeghedi 3 หลายเดือนก่อน

      Same here

  • @ThEldeRS
    @ThEldeRS ปีที่แล้ว +44

    I think that the biggest thing I’ve learned from this video is actually the Awaited type. I’ve been wondering if something like that exists since yesterday!!! Thanks for the great video, Jack! Hope that you and your wife are doing great 🙂

    • @jherr
      @jherr  ปีที่แล้ว +6

      We are. Thank you for asking.

    • @JEM_GG
      @JEM_GG ปีที่แล้ว

      Agreed! I've just used it on a App dir/Drizzle/fetch setup and it worked quite well with handing types from server components to client

    • @Labastidaa
      @Labastidaa 10 หลายเดือนก่อน

      Same here, that awaited type is very useful. Thanks for the video Jack!

  • @cryptoaddict6715
    @cryptoaddict6715 ปีที่แล้ว +4

    The timing of me finding this is perfect. Thank you for your time. You're helping me learn as I go .ore than I can say.

  • @yurisoares2596
    @yurisoares2596 9 หลายเดือนก่อน +2

    Awesome.
    This is the third vídeo I have seen about tRPC, and this was the best out there. Even since the setup is really similar to the T3.

    • @bytequest1552
      @bytequest1552 9 หลายเดือนก่อน

      Is is working?

  • @mertdr
    @mertdr ปีที่แล้ว +20

    Perfect timing Jack! I’ve been thinking trpc and react query has become irrelevant after app directory released but apparently they’re more relevant than ever because of app dir’s persistant caching issue. Actually I’m not even sure if it’s an issue or intended behavior because next team hasn’t provided a proper solution for months.

    • @YordisPrieto
      @YordisPrieto ปีที่แล้ว

      What issue are you referring to if you do not mind to share? Is there any particular Issue or Discussion opened?

    • @mertdr
      @mertdr ปีที่แล้ว

      @@YordisPrieto it’s about server component’s caching. Next team somehow decided a 30 seconds minimum caching for server components and revalidate value cannot change it. As far as I’m concerned it’s something similar to opcache of php. It’s mainly for html content inside of a server component but I noticed it also affects fetching as well. There was a discussion on github to provide a new global similar to revalidate in order to override caching time but it’s not implemented yet. That being said, mutations or refetching is not handled properly without additional methods like router.refresh() etc. and it complicates things. Many people had issues about this “cached by default” approach.

    • @YordisPrieto
      @YordisPrieto ปีที่แล้ว

      @@mertdr that explained what happened to me. Debugged for ours Nats message passing because I couldn’t figure out why my next page didn’t show the results… until I opened the console and forced the cache to be invalid … never understood the duck was going on until now … really stupid if you ask me

    • @mertdr
      @mertdr ปีที่แล้ว

      @@YordisPrieto I switched to TRPC the day I posted the comment above so I remember the actual problem vaguely. As far as I can remember router.refresh() didn't help to invalidate fetch calls in server component, which is a huge problem. Caching is vital part of applications but like you said cached by default approach is not sensible and brings more problems than it resolves. I got used to server/client components and enjoy the concept very much but there are still so many things to iron out.

  • @tamir.s
    @tamir.s ปีที่แล้ว +3

    Another great video from you, Jack, thank you very much!
    I wish I could watch that few weeks ago, it could save me so much time wasted on figuring it out on my own.
    But I still decided to move away from tRPC for now, as I didn't know how to add and connect the other important layers that you covered in your older video, like creating the context with stuff you need like prisma, and oAuth.
    It will be really helpful if you continue where you left off in this video with these topics.
    Much appreciation and love to you and your family!

  • @MikeyUchiha
    @MikeyUchiha ปีที่แล้ว +14

    If it's not too much to ask, I would really appreciate a couple if things to expand on this.
    1. Showing how to use the db as a context in TRPC like how T3 stack does it.
    2. Show how to use context in TRPC for Clerk.
    This couple of pieces would offer a complete replacement and comparison to the T3 stack not providing support for App Directory but still leverage some of the good practices that are part of the framework.
    Thanks for your time and consideration.

    • @ovidiuk2
      @ovidiuk2 ปีที่แล้ว +2

      I am also looking for some details about how to use context for implementing Clerk with TRPC in this setup

    • @rogueturnip
      @rogueturnip ปีที่แล้ว

      @@ovidiuk2 I'm getting closer. this works but always fails on auth right now. maybe it will help you solve it
      context.ts next to the trpc.ts file
      import * as trpcNext from '@trpc/server/adapters/next';
      import {
      SignedInAuthObject,
      SignedOutAuthObject,
      getAuth,
      } from '@clerk/nextjs/server';
      // import { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch';
      import { inferAsyncReturnType } from '@trpc/server';
      interface AuthContext {
      auth: SignedInAuthObject | SignedOutAuthObject;
      }
      export const createContextInner = async ({ auth }: AuthContext) => {
      return {
      auth,
      };
      };
      export const createContext = async (
      opts: trpcNext.CreateNextContextOptions
      ) => {
      const context = await createContextInner({ auth: getAuth(opts.req) });
      return context;
      };
      export type Context = inferAsyncReturnType;
      update trpc.ts to
      import { TRPCError, initTRPC } from '@trpc/server';
      import type { Context } from './context';
      const t = initTRPC.context().create();
      export const router = t.router;
      export const middleware = t.middleware;
      export const mergeRouters = t.mergeRouters;
      const isAuthed = t.middleware((opts) => {
      const { ctx } = opts;
      if (!ctx.auth?.user?.id) {
      throw new TRPCError({ code: 'UNAUTHORIZED' });
      }
      return opts.next({
      ctx: {
      user: ctx.auth.user,
      },
      });
      });
      export const publicProcedure = t.procedure.use(isAuthed);
      change route.ts to
      import { NextRequest } from 'next/server';
      /* eslint-disable @typescript-eslint/no-explicit-any */
      import { appRouter } from '@/server';
      import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
      import { getAuth } from '@clerk/nextjs/server';
      const handler = (req: NextRequest) =>
      fetchRequestHandler({
      endpoint: '/api/trpc',
      req,
      router: appRouter,
      createContext: () => ({ auth: getAuth(req) }),
      });
      export { handler as GET, handler as POST };

    • @rogueturnip
      @rogueturnip ปีที่แล้ว

      I got it fully working.. not sure if this is best practices or not but what I found is you can't pass the auth from clerk on the server fetch, but you don't need too cause your page should be auth'd too. So what I did was updated the context.ts file to handle no context from server by putting in a userId===system.
      /* eslint-disable @typescript-eslint/no-explicit-any */
      import * as trpcNext from '@trpc/server/adapters/next';
      import { getAuth } from '@clerk/nextjs/server';
      // import { FetchCreateContextFnOptions } from '@trpc/server/adapters/fetch';
      import { inferAsyncReturnType } from '@trpc/server';
      export const createContextInner = (req: any) => {
      if (!req) {
      return { auth: { userId: 'system' } };
      }
      return {
      auth: getAuth(req),
      };
      };
      export const createContext = async (
      opts: trpcNext.CreateNextContextOptions
      ) => {
      const contextInner = createContextInner(opts.req);
      return {
      ...contextInner,
      req: opts.req,
      res: opts.res,
      };
      };
      export type Context = inferAsyncReturnType;
      then you modify the serverClient.ts to
      import { appRouter } from '@/server';
      import { createContextInner } from '@/server/context';
      export const serverClient = appRouter.createCaller(
      createContextInner(undefined)
      );
      @jherr

    • @IcedTears
      @IcedTears ปีที่แล้ว +4

      Not sure the best approach for this but in my case I've created a createTRPCContext function that return my db object:
      export const createTRPCContext = () => {
      return {
      db,
      };
      };
      Then I used this in the init function:
      const t = initTRPC.context().create({
      when creating the serverClient:
      export const serverClient = appRouter.createCaller(createTRPCContext());
      and in the handler:
      const handler = (req: Request) =>
      fetchRequestHandler({
      endpoint: "/api/trpc",
      req,
      router: appRouter,
      createContext: createTRPCContext,
      });
      For Clerk in your trpc file:
      const isAuthed = t.middleware(async ({ next }) => {
      const user = await currentUser();
      if (!user) {
      throw new TRPCError({ code: "UNAUTHORIZED", message: "Not authenticated" });
      }
      return next({
      ctx: {
      user: user,
      },
      });
      });
      export const protectedProcedure = t.procedure.use(isAuthed);
      Now your protected procedure are going to have user within the context

    • @paweknot9047
      @paweknot9047 ปีที่แล้ว +1

      @@IcedTears thanks pal, thats exactly what I needed for clerk

  • @mjohnson510
    @mjohnson510 ปีที่แล้ว +4

    Omg! This is a game changer!
    I really liked trpc and didn’t want to move away from it

  • @mauricioyepes3394
    @mauricioyepes3394 ปีที่แล้ว +2

    Hi Jack, this is the first video I've watched on your channel, and you've saved me an incredible amount of time. I'm a new follower here. Thank you!!

    • @jherr
      @jherr  ปีที่แล้ว

      Thanks! Happy to have helped.

  • @MikeyUchiha
    @MikeyUchiha ปีที่แล้ว +1

    I have never subscribed so fast. I have been waiting over a month for someone to finally show how to do this. You are the GOAT. Thank you 😊

  • @khushalbhardwaj6192
    @khushalbhardwaj6192 ปีที่แล้ว +5

    There's hasn't been a video on how to set up tRPC on the app router for such a long time. I had stopped using tRPC in the projects after I switched to APP Router, after seeing this video I'm probably back at it.
    Thanks for this 👏

  • @ShaunCullen
    @ShaunCullen ปีที่แล้ว +5

    Looking at the type spaghetti at @17:40 on line 10:
    Now we C++'n.
    But seriously this is really cool, thanks for the full end to end walk through Jack.

    • @BeBoBE
      @BeBoBE ปีที่แล้ว

      tRPC has a utility type for this exact situation called inferRouterOutputs to retrieve the outputs of each endpoint

  • @edwardselirah4764
    @edwardselirah4764 6 หลายเดือนก่อน +1

    Just had a project and I had to understand tPRC quick. This was the right video for me. Thanks

  • @merveillevaneck5906
    @merveillevaneck5906 ปีที่แล้ว +4

    LOVE IT!!!! i literally did EXACTLY this about 2 months ago when setting up our new internal R&D project and i gotta say the TRPC + app router + drizzle combo is just pure bliss. great to see some tested content on the topic!!

  • @oscarljimenez5717
    @oscarljimenez5717 ปีที่แล้ว +14

    Amazing video. Actually you can even do streaming with tRPC 👀, and they have a experimental package for server actions too. And in RQ to avoid the second request, is better to set stale time to 30 globally, that's what TkDodo is going to do in the next version to avoid this.

  • @Its-InderjeetSinghGill
    @Its-InderjeetSinghGill ปีที่แล้ว +3

    You made my day. Currently TRPC with next 12 kinda sucks because came across some issues like caching and couldn't figure out why trpc making same request when we reload our page which is not as performant and it eats up lot of database usage. May be I am wrong with the caching problem because I tried what you have suggested at 18:22 but it didn't work in my case. But now I am going to use TRPC with next 13 confidently only because of you. Thanks

  • @TheRoseWoodBody
    @TheRoseWoodBody ปีที่แล้ว +5

    Thanks, Jack! It's exactly what I've been looking for.

  • @zustandslos
    @zustandslos หลายเดือนก่อน +1

    such a great video, helped my really good to understand how trpc works with the app router, thanks :)

  • @wagnermoreira786
    @wagnermoreira786 9 หลายเดือนก่อน +1

    What an aaaawesome video! thanks so much Jack! This is just what I was looking for :)

  • @GuilhermeSiebert
    @GuilhermeSiebert 8 หลายเดือนก่อน

    Wow, it's just Monday and you have already saved me the full week! Thank you so much.
    Subscribed!

  • @AvihuTurzion
    @AvihuTurzion 3 หลายเดือนก่อน +1

    Amazing walkthrough
    Lerned so much in such a short amount of time

  • @victortriathlete
    @victortriathlete 9 หลายเดือนก่อน +1

    Amazing introduction to integrating tRPC into the NextJS app router.

  • @iSkreme
    @iSkreme ปีที่แล้ว

    You crushed this; taught us how to create a dynamic SSR web-app with database in under 20 minutes....

  • @Furki4_4
    @Furki4_4 ปีที่แล้ว

    Thank you so much! I was searching for a way to implement tRPC with the app directory. This video explains everything very clearly!

  • @xanthe7045
    @xanthe7045 ปีที่แล้ว

    Always love your content. I'm creating an app that is using Nextjs 13 app + tRPC. and this video was just what I needed. Thanks.

  • @teetanrobotics5363
    @teetanrobotics5363 ปีที่แล้ว

    "Hey Tom! Just wanted to drop by and let you know how much I'm loving your content, especially your T3 Stack, TRPC tutorials, and Next.js guides. Your explanations are clear and really help me grasp these concepts better. 🚀
    I'm eagerly looking forward to more of your tutorials in the future. If you could create more content like this, it would be amazing! Your insights and tutorials are a great resource for learners like me. Keep up the fantastic work and keep those tutorials coming! 👍📚"

    • @jherr
      @jherr  ปีที่แล้ว +5

      Thanks! Name is Jack though.

    • @kickbuttowsk2i
      @kickbuttowsk2i ปีที่แล้ว

      ​@@jherrlol

  • @MuhammadHanann
    @MuhammadHanann 10 หลายเดือนก่อน +1

    Thank You So Much Sir. Before your video tRPC was a rocket science for me.

  • @davidhavl
    @davidhavl ปีที่แล้ว +1

    Fantastic. Thank you for the good work and for educating the dev world the right way!!

  • @nicolascalathus7349
    @nicolascalathus7349 ปีที่แล้ว +6

    It would be very enlightening to see a video where you showcase tRPC against the server actions way of doing things to clarify why tRPC.

  • @eovandodev
    @eovandodev ปีที่แล้ว +1

    This is what I've be waiting for! Thanks Jack

  • @noor_codes
    @noor_codes ปีที่แล้ว +1

    Such a great video, straight and easy to understand. I just hope you dived deeper into the important things like how to add the db into the context so you can access it all over the place and also explain middlewares and how that works with authentication.
    I would love to see a video on that, the official docs do not cover app-router on nextjs

  • @josephdburdick
    @josephdburdick ปีที่แล้ว

    I was racking my brainz over this all weekend and finally found your video. Liked and subscribed, thank you.

  • @mubin-ansari
    @mubin-ansari ปีที่แล้ว +5

    I always loved tRPC and was disappointed to see it not sustained in the app directory workflow. Super excited to see this setup, and can't wait to use it in my future projects!!

  • @randomuser6789
    @randomuser6789 ปีที่แล้ว +1

    Extremely high quality content, thank you very much

  • @phranjay2545
    @phranjay2545 7 หลายเดือนก่อน

    You have no idea how much you have helped me, thank you for what you do

  • @WahyudinataSetiawan
    @WahyudinataSetiawan 2 หลายเดือนก่อน

    this helped me much better than trpc doc itself
    PS: there is an update to the TRPC function signatures, createCaller is replaced with createCallerFactory

    • @KayKhan-x1c
      @KayKhan-x1c 2 หลายเดือนก่อน

      Can i see the example code of what you changed?

  • @TheIpicon
    @TheIpicon ปีที่แล้ว +3

    Beautiful video!
    missing app router trpc integration is one of the feew reasons people don't move to the app router yet.

    • @gadgetboyplaysmc
      @gadgetboyplaysmc ปีที่แล้ว +1

      Also the router caching problems tho

  • @tarzan7994
    @tarzan7994 ปีที่แล้ว +1

    Incredible video Jack honestly you've helped me progress massively throughout my coding journey. I was only starting to implement typescript in one of my projects and was faced with how to implement trpc in the app router so your video came at the perfect time. Any chance there will be a further video explaining how to implement optimistic UI updates using this pattern? Thanks again for all the content!

  • @adlerspencer
    @adlerspencer ปีที่แล้ว +1

    Amazing, Mr. Herrington! Thank you!

  • @andriiantoniuk8419
    @andriiantoniuk8419 ปีที่แล้ว +1

    This is excellent!!! Thanks for the video :)

  • @FutureExC-gd7zv
    @FutureExC-gd7zv 5 หลายเดือนก่อน +1

    Crystal clear explanation.

  • @abhinav.sharma
    @abhinav.sharma ปีที่แล้ว +2

    Exactly the video I was looking for JACK!

  • @AlbertPak
    @AlbertPak ปีที่แล้ว +2

    as always - quality content :)

  • @asimalqasmi7316
    @asimalqasmi7316 ปีที่แล้ว

    Thanks a lot for this awesome video. I saw it twice and maybe I will see it again tell I grasp the ideas from it.

  • @noccer
    @noccer ปีที่แล้ว +1

    A really great walkthrough, thanks a lot! ☘

  • @Dgiulian
    @Dgiulian ปีที่แล้ว +1

    Amazing, love the stack. I'm going to try it myself.

  • @oggy112
    @oggy112 ปีที่แล้ว +1

    Jack, you're absolutely amazing.

  • @MattChinander
    @MattChinander ปีที่แล้ว

    The flashes of the white background browser and terminal are brutal to my eyes.

  • @roba998877
    @roba998877 3 หลายเดือนก่อน +1

    Amazing video! I’d love to see how to best do error handling if you’re looking for video ideas 😊

  • @snatvb
    @snatvb ปีที่แล้ว

    many thanks for the video, really helpful and looks better than server actions that's experemental

  • @exponent42
    @exponent42 ปีที่แล้ว +11

    please correct me if I'm wrong, but isn't TRPC redundant with server actions? they're fully typed e2e?

    • @filipjnc
      @filipjnc ปีที่แล้ว +2

      Server actions are alpha/experimental still. Plus, nextjs doesn‘t really promote fetching data in client components with server actions. I use RSC patterns in server components + tRPC in client components and it works wonders.

    • @asutula5797
      @asutula5797 ปีที่แล้ว +1

      Maybe you're implying something about "fetching" data vs mutating data on the server, but as far as I can tell fetching data works fine.

    • @filipjnc
      @filipjnc ปีที่แล้ว

      @@asutula5797 it works, but nobody from Next.js promotes this solution in the docs and the caching story is unknown or even non existent.

    • @exponent42
      @exponent42 ปีที่แล้ว

      @@filipjnc thanks, that does make sense

  • @xWildStorm7x
    @xWildStorm7x ปีที่แล้ว +5

    Hello Jack, thanks for the awesome video!
    I have a question, I added a context to my TRPC app router and now I am getting a type error on the serverClient. It asks me to pass it the context. In the TRPC docs it indicates to pass the context like this: createCaller(await createContext()) but I get a type error saying the createContext function expects to receive req and res params. Not sure what to do since I don't have access to req and res in this file. Do you know how to solve this issue? Any guidance will be appreciated

  • @RaduCiocan
    @RaduCiocan ปีที่แล้ว +50

    could you make one to for nextauth+drizzle+trpc+appdir? (nextauth just added drizzle support)

    • @jherr
      @jherr  ปีที่แล้ว +17

      You mean just add nextauth to this?

    • @RaduCiocan
      @RaduCiocan ปีที่แล้ว +2

      that will be a good addition@@jherr

    • @RaduCiocan
      @RaduCiocan ปีที่แล้ว

      thanks, I did not known they made it @@Fuzbo_

    • @lukeweston1234
      @lukeweston1234 ปีที่แล้ว

      I really don’t understand what next auth is offering. I was surprised to see there’s no support for things like password reset

    • @carlosricardoziegler2650
      @carlosricardoziegler2650 ปีที่แล้ว

      Will be interesting a video to use next-auth with some external api. Imagine that you have a backend and need to integrate with into new next app with next-auth. This is a good approach or better to use another custom solution?

  • @mayrarincones8427
    @mayrarincones8427 8 หลายเดือนก่อน

    Thank you!! this was really helpful ❤

  • @GringoDotDev
    @GringoDotDev ปีที่แล้ว +12

    Really good video! For me though the bigger question re: tRPC + Next 13 is "why?" Seems like once server actions are more stable, there won't be so much need in the stack for a typesafe way to call the backend from the frontend. Unless, I suppose, you want a SPA architecture e.g. for easy extraction to Capacitor or something.

    • @onta.nicolae
      @onta.nicolae ปีที่แล้ว

      same question here

    • @filipjnc
      @filipjnc ปีที่แล้ว +10

      Well server actions do not help you with fetching data in client components. And if you say: just pass it down from the server component - you can only do so when you can bind the behavior of your client component to something your server can access too: URL path, cookies, etc. What if your client component is highly interactive and needs to fetch data on the fly, e.g. combobox with server side filtering? In this case neither RSC fetching nor server actions will help you much.
      You can use server actions to fetch data for you in the client component, but nobody (including the Next team) seems to promote that. I think the caching story there is non existent.

    • @GringoDotDev
      @GringoDotDev ปีที่แล้ว +2

      @@filipjncmakes a lot of sense, thanks!

    • @PyrexCelso
      @PyrexCelso ปีที่แล้ว

      @@filipjnc why can't you use a server action that returns the data and then query it with startTransition?

    • @filipjnc
      @filipjnc ปีที่แล้ว

      @@PyrexCelso i’m not saying you can’t. I’m saying that this approach is described nowhere in the docs or anywhere in any tutorial, which means it is probably not an intended use. Also, I think server action responses are not cached in any way - making them not the best for data fetching scenarios.

  • @willurban837
    @willurban837 ปีที่แล้ว

    AMAZING, thanks for the video!

  • @tomaszbazelczuk4987
    @tomaszbazelczuk4987 ปีที่แล้ว +1

    Great video as usual 👍

  • @raygan3
    @raygan3 ปีที่แล้ว +4

    I don't get why do we need to make a http requests using serverClient if we are already on the server (server component), can't we just call the server procedure? why the http link is needed?

  • @zachmeyer_
    @zachmeyer_ ปีที่แล้ว +2

    Curious why not just use NextJS server actions? Wouldn't that still maintian typesaftey across the client server boundry?

  • @lemonz445
    @lemonz445 2 หลายเดือนก่อน

    Would love to learn more about the serialization that happens from server -> client compared to the SuperJSON transform. Just spent a few hours struggling to figure out why my initialData had a bigint that was a string... and I'm fairly sure it's the RSC serialization that isn't SuperJSON-based. It seems like tRPC has _some_ docs on prefetching/dehydrating but I can't get it to work in the app router.

  • @berleytrails
    @berleytrails ปีที่แล้ว +1

    Great video! Thanks

  • @shteev
    @shteev ปีที่แล้ว

    Great stuff! I may be jumping the gun as I haven't finished the video just yet, but you're saying that we have to use "use client" and react query to interact with our server code, and I'm sure it's possible to bypass all that using server components plus server actions within the form action attribute.

  • @MascleGinger
    @MascleGinger ปีที่แล้ว +1

    Jack, your content is just the next level! I am wondering how do you manage to do a full time software development job and provide such a high quality content

    • @jherr
      @jherr  ปีที่แล้ว +3

      I don't. I'm now a full time content creator.

  • @JEM_GG
    @JEM_GG ปีที่แล้ว +1

    So cool thanks Jack!

  • @kosti2647
    @kosti2647 ปีที่แล้ว +1

    the explanation was really good! I'm struggling to add next-auth session to server client, do u think u could extend this repo to also have next auth session implementation? I think many folks could use such video, having auth is common thing nowadays. I'm not sure how to have user context/session available in trpc context

  • @bibblebabl
    @bibblebabl ปีที่แล้ว

    Hi Jack! Thanks for the video! BTW, what kind of zsh theme/plugin are you using?

  • @tzuilee588
    @tzuilee588 ปีที่แล้ว +1

    Wow this one is amazing

  • @NicolasVegaTerrazas
    @NicolasVegaTerrazas ปีที่แล้ว +2

    Awesome video! One question: when typing initialTodos why didnt you use the trpc built in methods to infer the types of the procedures inputs/outputs? Is there any particular reason ? You could save some verbosity.

    • @jherr
      @jherr  ปีที่แล้ว +1

      Can you give me an example of that?

    • @NicolasVegaTerrazas
      @NicolasVegaTerrazas ปีที่แล้ว

      @@jherr and you can also use some convenience methods: type RouterInput = inferRouterInputs;
      type RouterOutput = inferRouterOutputs;

    • @NicolasVegaTerrazas
      @NicolasVegaTerrazas ปีที่แล้ว

      ​@@jherr the main tradeoff is that your component is tied to the type of your resolver output type, and not to the type of function wrapping the backend call.

  • @StabilDEV
    @StabilDEV ปีที่แล้ว

    Superb video, thanks a lot! What is the advantage of putting client.ts and serverClient.ts into app/_trpc instead of e.g. lib or utils outside of the app dir?

  • @killiangemoets1360
    @killiangemoets1360 5 หลายเดือนก่อน

    Hi Jack, love your content! A few thoughts:
    - Wouldn't be nice to use server actions to create a new item instead?
    - Why using ssr at first and then csr on revalidation? Would it be interesting to use ssr on revalidation as well? I guess your approach if more performant?

    • @jherr
      @jherr  5 หลายเดือนก่อน

      When I do a video on a technology like tRPC, what I'm looking to do is to focus the content of the video on that topic. So in this case I want to show queries and mutations using tRPC to demonstrate tRPC. Is tRPC the right choice on the App Router? Totally up to you. But if you decide to use it, then you can use this video as a reference for that. It's not meant to indicate that in all circumnstances that tRPC is the correct choice architecturally. If you can get away with it, server actions are far easier.

  • @gosnooky
    @gosnooky ปีที่แล้ว

    My issues with this is at 17:25, where there's all that boilerplate TS code Awaited, ReturnType and typeof and indexed type property, when I just prefer a type or class that is Array. I also find the pattern that a LOT of TS devs are using where the type object is inlined with destructuring, it's hard to read that code. It's cleaner to write
    interface Props { initialTodos: Array }, then function TodoList(props: Props) {...}. It's much cleaner I think.

    • @jherr
      @jherr  ปีที่แล้ว

      AFAIK, you can do that. You could declare a Todo that is shared between the tRPC endpoint and the UI. You'd need to synchronize it with what's coming out of the DB. And if it matches that's fine. I used the utility types here because they naturally track with the output of the API endpoint.

  • @oscaresteve5344
    @oscaresteve5344 ปีที่แล้ว +1

    Great video! Would be fantastic to have a video handling validation error from Zod :)

  • @lobataros
    @lobataros ปีที่แล้ว

    Hi mr. Herrington, this is out of topic, but i wondering what zsh theme did you use? I love the fonts also the color combination of your terminal

  • @vazus171
    @vazus171 ปีที่แล้ว +1

    Hi Jack,
    Great video! However I've noticed an issue. In 16:10 you are creating a caller and pass links there. But tRPC caller accepts context rather than config, so now you have this weird context on server.
    I've tried to get "normal" context preserver, but failed. Not sure how it can be done with App router. I have NextAuth to create a session and want to always preserve this session on context, so it can be used in middleware for protected routes. Any ideas on how to do it?

  • @martinfulop484
    @martinfulop484 10 หลายเดือนก่อน

    Hi Jack! May I know which VSCode theme and font are you using? I love it.

  • @tonybenci2796
    @tonybenci2796 11 หลายเดือนก่อน +1

    Hi Jack. I was having an issue with 1 line of code :).
    In client.ts your example shows
    import { type AppRouter } from "@/server";
    I believe that this ensures only the type is imported without importing the actual module at runtime. Problem is (with both prettier and typescript at latest versions as of today) Prettier said no.
    ',' expected. (3:15)
    1 | import { createTRPCReact } from "@trpc/react-query";
    2 |
    > 3 | import { type AppRouter } from "@/server";
    I initially removed the type but realised that that's going to import the module.
    I then changed it to the following syntax
    import type { AppRouter } from "@/server";
    And everyone was a happy camper. Is your syntax more correct? And, if so, how to we get Prettier to cooperate?
    Thanks
    Tony

    • @jherr
      @jherr  11 หลายเดือนก่อน

      AFAIK, both work but I do prefer the type outside actually.

  • @sujeet4410
    @sujeet4410 ปีที่แล้ว +2

    Hey Jack. Which Zsh theme are you using?

    • @jherr
      @jherr  ปีที่แล้ว

      Oh-my-posh with the Atomic theme using the Spacemono NF font.

    • @sujeet4410
      @sujeet4410 ปีที่แล้ว

      @@jherrthanks a ton. appreciate it. 🙌

  • @trixn4285
    @trixn4285 11 หลายเดือนก่อน

    Great Vid, thank you.

    • @jherr
      @jherr  11 หลายเดือนก่อน +2

      Server Actions give you type safety and a very easy API for the React code on the browser client to call... but... they don't give you an API that is convenient for any other client. So if you also have a mobile app, or a desktop app, or a CLI that needs to hit that API then they'll be reverse engineering NextJS form posts to make that same requests. And that's not a great API.
      So, it depends. If you are just doing a NextJS app, cool, use server actions. If you are doing NextJS + Mobile (or more) then I would either use an API + server actions, or just the API.

  • @seannewell397
    @seannewell397 ปีที่แล้ว +1

    This is awesome!

  • @binh1298ify
    @binh1298ify 4 หลายเดือนก่อน

    Thanks, Mr Herrington, very helpful video. Although I wish it was postgres instead of sqlite

    • @jherr
      @jherr  4 หลายเดือนก่อน

      Should be pretty straightforward to swap out sqlite for Postgres. They are both SQL databases and in this simple usage context are essentially identical.

    • @binh1298ify
      @binh1298ify 4 หลายเดือนก่อน

      @@jherr ahhh yes, i had done it before i made the comment

  • @infisspablo8602
    @infisspablo8602 ปีที่แล้ว

    Would u say using trpc with app router is better or just do fetching with functions and using setver wctions for mutating the data?

  • @electrpaleo
    @electrpaleo ปีที่แล้ว

    Great video! but I have a question, how can I do a server side call if my trpc router is hosted separately?

  • @computing1
    @computing1 ปีที่แล้ว +1

    How would you deploy the serverClient to something like vercel? Specifically, for the httpLink url, what do you put there?

  • @Moe-Ali11
    @Moe-Ali11 ปีที่แล้ว +1

    Great video!

  • @djuka8121
    @djuka8121 5 หลายเดือนก่อน +1

    Why aren't they documenting the app router on their trpc docs page?

  • @0x3334
    @0x3334 ปีที่แล้ว

    thanks for the video jack! as always, super quality stuff! i have a question… have you tried using transform in the trpc react client? trying to use superjson but haven't been able to make it work, the docs seem out of date. cheers

    • @jherr
      @jherr  ปีที่แล้ว +1

      You could use a useMemo to transform the output on the client. That's one option.

    • @0x3334
      @0x3334 ปีที่แล้ว

      @@jherr not sure how useMemo fits in, since the transform is supposed to be applied to the createTRPCReact directly as it's being created, analogous to the initTRPC.create method. i'll look into your suggestion, thanks a lot for taking the time to answer!

    • @jherr
      @jherr  ปีที่แล้ว

      @@0x3334 If what you are trying to do is transform the data coming back from the tRPC request, then just put that transform in a useMemo and make the data returned from the tRPC call a dependency. Maybe I'm missing the point, what is the transform supposed to do?

    • @IcedTears
      @IcedTears ปีที่แล้ว +1

      Client side you can add the transformer to the Provider inside the api.createClient call, server side inside initTRPC.create.
      I just figured this out, and still need some testing, but hopefully it helps.

    • @jherr
      @jherr  ปีที่แล้ว

      @@IcedTears What are you using the transformer for? Is there some specific type of serialization/deserialization that you need to control?

  • @sebcuadros
    @sebcuadros ปีที่แล้ว +1

    So good thx Jack

  • @huynhhoangphuc9027
    @huynhhoangphuc9027 ปีที่แล้ว

    Amazing ! Thanks Jack
    I really like your vscode theme, please tell me which theme you use

  • @tomirodriguez7195
    @tomirodriguez7195 ปีที่แล้ว

    The think that makes me a bit of noice about trpc and SSC is that you're basically calling your own server from the server to do some action, such as calling your db. I see no point on calling an endpoint, for most cases, when you can do it inside your component.
    I do still find it useful client side (at least till actions are stable), not only to use tanstak query functionalities (which are awesome) but also to have that nice typing when you call and enpoint.

    • @jherr
      @jherr  ปีที่แล้ว +1

      Coupla things, first you are calling, at least in this case, on the local loopback, so it's not that slow. And you benefit from the fetch cache if you call it from multiple places. But if you wanted you could pull out the tRPC function code into a vanilla function and then call that directly. And you could wrap that in a React `cache`.

    • @tomirodriguez7195
      @tomirodriguez7195 ปีที่แล้ว

      @@jherr thanks for your response!
      I agree with all the things you said. It’s not that slow making that calls through TRPC. I still think it’s a great tool, but at least for me, it’s just the fact that the same result comes out of the box with Server Components.

    • @jherr
      @jherr  ปีที่แล้ว +2

      @@tomirodriguez7195 A few folks have mentioned that, and I get it. To do _precisely this example_ in a single tier you don't need tRPC. That's one of the problems of picking an example to show. If I showed an example that showed a monorepo setup, with the tRPC server in a Nest app, a NextJS app that consumes it, and then say a React-Native App that also consumes it, that would be a much better demonstration. But it would also be an hour long video that few would watch.

  • @michaeldausmann6066
    @michaeldausmann6066 ปีที่แล้ว

    Thanks so much Jack for putting this together, it does indeed work in my Next app. Couple of points
    I think that Provider.tsx and the 'Provider' export name is a little ambiguous, maybe something like TrpcQueryProvider would be more explicit?
    the example is obviously simple with a single trpc router but in my app, I have built a number of trpc routers for different bits of the application and composed them together to make an app router. I think this is pretty common.
    I don't really get the double wrapping (trpc.Provider -> QueryClientProvider -> children) in Provider.tsx. Also needing to 'wrap' the children element in layout.tsx is pretty lumpy. I personally don't like using the component tree to get non-visual functionality as it conflates concerns (see zustand over context for e.g... no wrapping in zustand).
    Overall, I get the distinct feeling that while this approach definitely works... and thanks again for putting it together... but it won't be the final way we use trpc in next with app router

    • @jherr
      @jherr  ปีที่แล้ว +1

      If you have less "lumpy" methods I'm all ears.

  • @rottenpancakes
    @rottenpancakes 9 หลายเดือนก่อน

    Hello Jack, it would be amazing if you could make another tutorial explaining the more advanced features of trpc together with next and tanstack. Holy hell i'm going crazy trying to get infinite queries to render on the server first and then work on the client. I get that you need to create a SSR helper, then prefetchInfininte, then use a HydrationBoundry, then dehydrate the state... or something. Yeah, there's no a lot of information about how to do it with the app router. It doesn't help that a lot of guides are outdated and use the old API.

  • @黃聖崴-r4r
    @黃聖崴-r4r ปีที่แล้ว

    I would like to ask for advice. I really appreciate your video. How should wsLink be configured for createClient if the WebSocket server is set to run on port 3001 according to the documentation?

  • @nedimarabaci
    @nedimarabaci ปีที่แล้ว +2

    amazing!

  • @RatherBeCancelledThanHandled
    @RatherBeCancelledThanHandled 5 หลายเดือนก่อน

    Wow I love your terminal ! Can you please share how you set that up ?

  • @集中-l7m
    @集中-l7m ปีที่แล้ว +1

    Nice video. Perhaps, client side type seems not intuitive for time being?

  • @Tiaguex
    @Tiaguex ปีที่แล้ว

    Nice terminal, can you provide some info of what themes are you using to have it?

  • @CodeClem
    @CodeClem 8 หลายเดือนก่อน

    Hey Jack, is it possible to use trpc with RTK-QUERY?

  • @wavyboyjodii
    @wavyboyjodii 7 หลายเดือนก่อน +1

    Thank You Sir

  • @2u675
    @2u675 7 หลายเดือนก่อน

    Thank you very much for sharing. Could you share your zsh configuration? It looks great.

  • @caincobain9318
    @caincobain9318 11 หลายเดือนก่อน +1

    Hey I know am late but I have a question if you don't mind, how do you handle types that are in the ORM modals like Date and are not supported by typescript ? like for the initalTodos with created_at field of type Date it's not working with react query ts for initialData (am using prisma btw). thx

    • @vizunaldth
      @vizunaldth 10 หลายเดือนก่อน

      fix posted