I Quit tRPC. Here's What I Do Instead
Вставка
- Опубліковано 22 сер 2024
- tRPC was and still is a good tool to quickly build full-stack projects. I stand by that. Here's why I haven't used it for months and the approach I've been using instead. This has worked super well for me, and I think it will for you too.
-- my links
My GitHub: github.com/jos...
Discord: / discord
Gotta say you’ve kinda missed the whole point of trpc, you didn’t have an “alternative” to trpc. You just hard coded what they do under the hood in a less secure way. Because now you have to actually infer each type and it’s not so different from type assertion with the only exception of throwing an error.
What trpc allows you is only once declare your types on the api handler itself(like a regular function) and automatically when you call it you get type safety without additional assertions or parsing(which can go wrong because of human error) and another huge win(one that Theo praises) is that the response is inferred automatically by what you return from the function, no need to type assert for the response
What would be your alternate suggestion?
Or rather, how to pick it up? Trpc is interesting to me, but if it's often times not up to date with the latest NextJS then that's a pretty big limitation to DX.
@@carlonnrivers personally I prefer to lay back and stay away from Next 13 because of limited library supports.
But once it progresses enough, I think obviously the server actions or going to be the trpc killer once they’re stable.
Another library that might kill trpc before server actions are stable(which is also still in beta I think), is Bling by TanStack(the team behind react query).
This library is very similar to what server actions are trying to achieve but started development long before server actions were announced.
Ofc that’s just my personal take on the subject
@TheIpicon I appreciate the insight. I'm just learning NextJS and finished some crash courses, so now on a journey recreating some of my past full stack applications with it, understandings it's pitfalls or not, and practicing/learning more about it. I'll look out for those libraries, though I also agree it needs to be complete soon.
trpc is hyper coupling your core code to the infrastructure. It's an amazing solution to a problem that only exists for shit programmers.
Have you heard about the ts-rest library? It basically what you are manually doing and I prefer it so much more over trpc. It has End to end type safety, RPC-like client side interface, Tiny bundle size, Well-tested, production ready, No Code Generation, Zod support for runtime type checks, Full optional OpenAPI integration. You should do a video about it, it's so much simpler.
Oh never heard about that, sounds useful. Appreciate the suggestion
ts-rest cannot be a better solution
i don't see how ts-rest can be simpler. it's literally tRPC with extra steps and their own RPC comparison page in their docs admit that. there are *some* use cases where you want a separate contract and backend fulfillment but for your average monolith this isn't the case.
zod is not a tRPC alternative... tRPC doesn't do any validation or parsing. it's even designed with libraries like zod in mind.
Really cool, but you still don't get auto completion for your endpoints, you have to know the api structure and what endpoint you want to hit, and manually atribute validators to them.
Cache optimization is gone too (missing react-query)
Genuine question (I'm not using JS/TS on the backend.) even from a perspective of a purely frontend dev, shouldn't one anyway know the api structure and endpoints?
@@denissorn They should. But imagine that there are hundreds of endpoints (which is very common) and some route changes. And that route is used in a lot of places of your frontend app.
If you access your api routes through typesafe object methods with auto completion (like with tRPC) then you instantly know where to make changes because you'll get typescript errors in every file you are using that endpoint.
Yeah you don't. It would've made sense for me to make clearer in the video this is not supposed to be a replacement, but an alternative way to achieve a good degree of type safety while also being able to stay up-to-date with the newest releases
tRPC is not just about type safety. It offers many features that help to create a solid workflow, such as Contexts and Middlewares. While NextJS does have middleware support, the granularity that tRPC offers is very useful in many cases. Implementing ACL in tRPC routes is very easy using metadata in contexts, and you can centralize all the checks in middlewares to prevent the user from forgetting to implement the correct roles in every route. In a large or multi-tenant application, these features come in very handy.
sweet! now all that's left is a full-stack drizzle tutorial.
Aw man you guys really wanna see that
It's crazy how in Javascript world we can say "in the past" meaning a couple of weeks ago lol
very good video and a fresh approach. And to the point... if you want to move fast with Next versions, tRPC is slow to follow.
However, I think you should've mentioned downsides of your approach too. It's not a replacement to tRPC and tRPC is not only for type safety. It makes you define types only once. In your case, you have to define ApiResponse types, while in tRPC it gets inferred "automatically".
Bro, the last few days your uploads been stressing me out. I started a new project with prisma, and you uploaded the prisma video, I have been using tRPC with the same project, and now this.
I love the content, and that you share your opinion on packages/tech as you use them. Keep it up.
This is still solid tech. It's important to understand the trade-offs that come with each. There is no best approach, as boring as that sounds. tRPC can make so much sense in certain scenarios, in others it might not.
With trpc i have no ability to acces the filesystem. I know that’s not the point of trpc, but that’s frustrating man, i just want to have something that does all.
Although i do understand what youre trying to do and it is what I have been doing for my projects where I do not use TRPC, I believe it is not correct to say that this gives any comparable degree of typesafety since the fact is axios response and request types are any/unkown so even if i give it an invalid type with an input that matches that type, it will happily oblige. This approach is the same one that people have used in the past as well, except that you are extracting types from the validator.
Drizzle video coming soon 😄
oh my lord everybody thirsty for a drizzle video
Hi Josh, I like your content, this one too. But I think you missed the mark on the messaging here. Since you just did a custom implementation of a small part of what TRPC does and is actually a much better solution if you only need that. I too am in the process of rewriting stuff into the app directory. However, when you start to think about authentication (public / protectedProcedure), refetching of stale data etc. You'll quickly realise you're going to implement a lot of stuff TRPC already does and in that case I'd suggest to use TRPC or something similar that is tested through time.
Yeah good point - I wish i had made it more clear this is not meant as a replacement but rather an alternative to provide a solid degree on typesafety in combination with the flexibility of using the lastest releases. It's always super important to me talking about WHY we're doing what we're doing
for mutation u can use server actions
and for fetching data u can fetch it directly if it is a server component
I think this is 90% of cases, isn't it ?
Not sure, but server actions aren't even in Beta and have all sorts of problems concering security and human error
That briliant idea, cool
I mean yeah this works, but it's not really more type safety than you'd get without zod. the point of tRPC is to get the client side inferred based on server side, so you don't have to do the validation in two places. And to have the types without any hussle. With this you could easily use the wrong validator on the FE and you'd get wrong response type out. And sure it's easy to find and fix, but it's something you need to do. with tRPC you don't need to do anything, you just api.your.endpoint.useMutation() and everything is handled.
Not saying this isn't a good approach, with next 13 and the app router this seems like the most sensible thing to do for a lot of use cases, and you can still throw in react query on top of it in a client component, give it server-side initial data and you'll be good.
still hoping they figure out something like tRPC. I don't even care about react query for it, I just want to write api.addTodo(payload) instead of api.post('/api/todo', payload) and have the types handled without extra code.
Well i feel good. I started doing this a few months ago on my own. Now that i see you are also doing this make s me feel good❤
Hey Josh, your VSCode setup looks like it is working real smoothly. My setup sucks! I can’t get my intellisense to work properly and I possibly have the wrong extensions. Would you mind sharing your configuration for VSCode with us noobs?
+
Same request
Of course, just not sure what you mean by "configuration". There's not a lot I changed, just installed a few add-ons and a dark mode theme. Is there a specific file or anything you're talking about?
@@joshtriedcoding plugins or what did you change? For example autoimport when you started to type, I don't have it by default.
@@joshtriedcoding Thanks for getting back to me - what I am referring to is your snippets file in VSCode that allows for code shortcuts. You must have the correct extensions as well to make it work as it is. I learn by often times coding with you but my VS Code behaves differently.
Hi guys. A couple of dumb questions:
1. Can't you just validate everything using regular typescript interfaces?
2. Is there a way to link your self made schemas shown in the video to an actual prisma schema (like trpc does)
3. Does it mean in order to not use trpc and still have typesafety, one has to define both input and output schemas and types for both input AND ouput, so 4 huge code blocks that are only slightly different from each other?
1. Input needs to be validate at runtime, TS can't do that. Josh also validate the response, that's not mandatory and most dev don't
2. You are mixing two very different things, the schema of you db is not the same thing as the schema of you api, you shouldn't mix the two. The schema of the api looks most of the time very different than the schema of you database.
3. Yeah you need to define input and output but only once because you wanna export the zod schema to the front (monorepo needed)
@@TheHouseTutorials Great explanations. Yeah validating the response is not mandatory and does not improve security (since you own the API), it's just for typesafety on the frontend. Alternatively you could just cast the response type as well
Why would you sacrifice all of that to work with the latest version of nextjs? At the end everything will change in about a year or two, I don't see it
What do you think of Zodios?
I feel like Trpc is too big too. But all sort of type completion and api loading state that came with it is just so good. Anyway nice to see you trying to make api typed without Trpc.
What do you mean by too big, the actual client-side footprint?
@@joshtriedcoding Sorry for vague words. I actually mean the starting code I have to write like routers and hook.
I guess that works for inputs, but is there a way to infer the return type of the route handler function?
Next API routes return a Response type, but you don’t seem to be able to get the exact type of the body response
Would be nice to have function calls like trpc to abstract the http verbs away
Server actions
Hey Josh, your content keeps getting better and better.
Gute Arbeit 👏
Gute arbeit ?
Cheers man
Why don't simply use Server Actions? Unless I need to go to production soon, I no longer see a use case for tRPC
Now, this is a good quality video!! Thank you! Explanation is clear and concise and also shows how to properly handle errors (which is what most videos don't care about, yet it is one of the most important parts of dev and differentiates good engineer from crappy one). Keep up the good work.
Error handling is so important. Appreciate it. Cheers
Great video! I love how happy you seemed when you said Flabbergasted
Great video man, thanks for the viable alternative. This is probably the worst time to start building a project with nextjs. Because it comes to quit tRpc, quit React Query, quit i18next and even quit redux (provider wrappers don’t look good, zustand is going to win this I guess). New Nextjs structure leaves behind so many great react and next js libraries. Let’s hope leaving those libs behind not cause a blowback.
Appreciate ya man, cheers. I don't think this is a bad time to start at all, in fact, it's probably the easiest it has ever been due to how many options you have. Although now there's so much to choose from, it can lead to something known as "paradox of choice". Pretty confident most libraries will adapt to the new environment
Why do you think zustand is going to win? To add context: I like the syntax, not sure how much traction the library has / will have
@@farastray1 because redux and also react query requires to wrap the app in a provider / react context. Since providers are client side functions, the only way to use a provider is to create a separate client component and render main app children inside of it. According to Nextjs documentation, all children of a client component will become a client component. In other words, server component features will be eliminated once you wrapped the app inside a client component. At least that’s what I understand. I read a lot about this and listened some core react dev team conversations however even they still don’t have all the answers. What they say is basically forget everything you know and try to understand this new architecture. As far as I can see the only upside of server components is fetching data before render at this time. I feel like there are still many potential questions on server components. Several top notch react libraries are still only suggesting workarounds for app folder.
react query, next auth (session provider) and redux requires their own client side providers. Why I said Zustand is a winner not because it’s better than redux but it doesn’t require a provider. By the way I always use Redux toolkit and don’t have much experience with Zustand but it’s quite popular.
@@mertdr check the docs, you can use the client component with the context inside the root layout, it's in the "react essentials" almost to the end where it talks about context.
@@AnnaGottinI know, it wasn’t the official solution before but apparently Vercel realized there is no other way than wrapping the entire project with client component. Next13 brings many great features but I still consider it in its beta stage. Because there are some weird (and changing) behaviors such as accessing headers, cookies and Josh mentioned recently about caching / revalidating issues. I wish they could have worked with maintainers of popular libraries like React query, trpc, i18next etc. for example yesterday I had to build my own i18n solution. It’s possible to build your own solutions for anything but is it really worth to break the ecosystem and going back to stone age by pulling the trigger so early?
This video seem to be aimed at beginners who'd like to avoid the lil complexity tRPC brings in and write more less-secure code because thats still his comfort zone.
I can never understand how you keep coming up with such good content 😭... I'm struggling to think of a video idea for a week lol
It's just whatever I find interesting or something cool I found out about. Nothing much to it honestly. You're going to do great
Sveltekit has type security already.
It’s crazy everyone missed the whole procedure output type amaziness of trpc!
Absolutelly amazing vid man, such a clear explanation on both your reasoning in a high level AND in the actual implementation.
Keep it up!
I know there are libraries outthere already, but currently writing my own one specifically for NextJS13 Route Handlers
As always a good video from you, Josh, greetings from Hamburg
this works great for POST request but not so much for GET requests that have query params. In which case you have to manually write them out before you can parse them with zod.
Feel like this is for the people stuck in tutorial hell.
what do you think about server actions?🤔 they seem game changing (though only experimental for now)…
i also really wanted to ask you: i prefer using backend separately and write rest API layer where next communicates with the server. but how should i implement that on client components? is it acceptable that they just share the same interface of requesting my server as server components do?
thank you a lot, i love your content
Honestly, I don't 100% understand your question, using a separate backend in Next works super well though. If you wanna fetch from client components, I'd recommend react-query for that
Why not just call your backend code inside the server components and keep the tRPC procedures for when you want to call the backend code from a client component ?
Even this becomes unnecessary if you use the new server actions. :) Most applications do not need API endpoints that are decoupled from the main web client.
Sometimes I like your video title more than the actual video.
You mind elaborating? Cause that's probably not how it should be
Very nice explaination of an alternative to tRPC. Thanks, Josh
{2023-06-28}
Yeah I get it. It’s not so bad. I suppose I need to write another wrapper to enable react query feature. It’s not as streamline as trpc but it’s not bad at all.
FANTASTIC video Josh, thank you. I was just researching how to replace tRPC and I think this is the best way we have... for now. While tRPC is great and all, Next 13's app router is just too good to not use meaning the few extra steps you have to do for type safety are negligible. I love Theo and the T3 stack, but the whole ideology behind it gives this idea that if you're not using it, you're doing it wrong-- which shouldn't be the case.
Agree. It's nice tech, just not for every situation. Hope this will work as well for you as it did and does for me
Would be awesome if you create a T3 Stack alternative. Specially given that today, most of T3 dependencies seem to be not a good idea.
For example, PRISMA -> Drizzle | NextJS Auth -> Clerk | TRPC -> ZOD | NextJS Pages -> App Directory
T3 is about building production ready apps. Using App directory for example is not production ready. it has lots of bugs.
drizzle is also not production ready, it is still in beta versions..
and replacing tRPC is no longer an argument if u are using nextJS pages . so everything u said is meaningless
plus drizzle is going back to cavemen days , prisma is the new standard for DX which translates to better UX.
"What do you use instead?" I don't know what tRPC is, I don't know what I use instead lol
I want to use graphql with a class based way like we did in nest or service based using apollo server in nextjs 13 app router i am not able to make the single endpoint http ....3000/graphql is there any way to use that
Hey Josh your video on Next Router is awesome I learn a lot thank you.
I am very grateful to you.
You're welcome dude
can you do a video how we can handle POST request coming from 'form-data' body format ? like if we want to handle file upload in nextjs REest API ???? Please
Out of interest what are the issues tRPC has with Next 13?
Hi, Josh. I have a question about using axios to fetch api. On regular fetch, there is option cache for api request. How the implementation that option in axios? Thanks
You can handle this on a per-page basis, for example forcing a dynamic or static behavior
do you have a full project that goes along with this?
so basically REST API with Zod :-)
I still think tRPC has more simplicity to it
Can the post request go to a server action instead of an API route? I have seen lots of examples of people making GET request in NextJS but almost nobody showing a POST that goes to a database. Thank you so much. If you make a video showing a Post using Mongoose to Mongo or a ORM going to PG or MySQL it would be greatly appreciated.
POST requests are exactly what server actions are for
Can you do a video what plugins do you use for vscode?
This is why svelte is just so much better. Switch and put an end to all this manufactured problems
Great Video Josh, I can relate to this trpc was becoming too bloated for me, seeing zod do so much makes me excited.
tRPC does add a lot of code and its own file structure to your project (even if just recommended), wasn't a fan of that either. Even if it made sense technically.
T3 stack is falling down... first Prisma, now tRPC
Is it worth using React Query in Next 13?
i just use Proxy
Josh i love you.
I have been learning so much from you even my senior dev doesn't expect how come a Jr dev knows this. Thank you so much Josh all of your next vids are amazing
That's so nice to hear. Means a lot man. Appreciate you
Completely agree
(theo satisfies Theo) wants to know your location.
hahahah
Fast becoming my favourite coding UA-camr. Great content and explanations.
Appreciate you man. Cheers
What do you need Axios for?
You never miss to make interesting content. Nice work
Happy to hear you enjoy the videos. Cheers dude
Unprocessessessessably excellent, great video!
hahaha
I think this could be more simple with next13 server actions.
Seems like a lot of work.
Hi Josh, Could you please make an i18next video with Next Js 13.4 tpesxript? Thank you for all your videos❤
types on JavaScript don't exist,
I have a project where I use trpc and react-query. There is no problem when I run the project in development environment but when I run it in prod environment when I get build. Get requests come when the page is loaded, my problem is that when I refresh the page, get requests do not come again. The problem only appears in the prod environment. I use trpc ssr : true. Have you encountered a problem like this or do you know the solution?
why do you use axios when you can use next fetch
cause I prefer axios syntax
saved a lots of hassle
Unprocessessesssessessessable Entity
Love the content 💗
I really wanted to ask you about this 😂
Really good explanation.
Amazing! Good bye T3!
nice.
this guys da goat
TRPC is better than Next 13.4
First 🎉🥇
What's this obsession people have with using axios?
nothing major, just a little cleaner syntax
@@joshtriedcoding and you think it's worth adding a dependency just because of that? Not trying to be a dick, but I've seen some new devs get the idea that it's ok to add countless libraries because they learn from UA-cam tutorials where doing stuff like that is naturalized. Axios is one of them.
Maybe you as an educator should give this some thought. It may not be immediately obvious but I personally think it does matter, and I know I'm not the only one.
Just my two cents bud!
@@allsunday1485 There are inherent pros to using it tho. Axios takes care of file upload progress for you. Good luck with a native solution
@@professorhuert7853 but that's completely missing the point. Nobody is arguing if axios has something to offer, because it's great. The point is that it's used in places where fetch is not only a completely viable option, but the best one, because it doesn't add an extra library.
Let's make this clear: the less external libraries the better. That's a fact.
If the library is required or worth the trade-off (a decision that's not necessarily trivial), let's go with it. But using axios when teaching how a GET request works? Using axios for a simple CRUD app in a code along tutorial that absolutely doesn't need it? That's the problem I'm talking about. The fact that you see it in every single video doing absolutely nothing to justify using it. Hence "naturalized".
It's common to find learners that completed a couple of tutorials and even projects of their own and have only used axios.
Native fetch is good and should be the default, unless there's a problem that justifies bringing axios in to solve it.
Sorry for the wall of text but I feel very strongly about this.