Next.js Discord

Discord Forum

Have anyone tried migration from TRPC router to app router api ( remove trpc )

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
I was trying to migrate from trpc to app router api route and got stuck, can anyone share resource or repo or something

85 Replies

maybe you want to check create-t3-app?
Sun bearOP
T3 stack uses TRPC
I want to migrate from trpc to app router api ( remove trpc )
oh sorry miss read it
what you got stuck with?
Sun bearOP
I don't know to migrate the api route my trpc routers
I'm not sure how to implement the procedure thing that trpc offers
why would you want to remove it?
Sun bearOP
we don't want to be locked in with trpc
app router api lack of middleware, meaning you have to do the checking for every route
Sun bearOP
how ??
const auth = await getAuth()
const isAdmin = await checkAdmin(auth)
const allowCreate = await canCreate(auth)
something like that
Sun bearOP
okay let me explain by using one of the trpc router
assume I have team router
and then it have bunch of protected route like adminprotected, memberprotected and protected procedures
and have bunch of create , update , patch and delete method
how am I gonna change that to api route in nextjs api
should I have to split them in to different route folder
app/api/teams/route.ts which have GET in it
app/api/teams/[id]/route.ts which have GET PATCH DELETE in it
app/api/teams/new/route.ts which have POST in it
and you have to check is the user an admin/member for every route
Sun bearOP
what about the ctx thing and input
input mean req.body ?
const data = await req.json() if you are posting with json body
@Sun bear input mean req.body ?
Sun bearOP
this is right ??
or const data = await req.formData() if you using formData
@Sun bear this is right ??
no its not correct in app router, use req.json() or req.formData()
Sun bearOP
to get the body sent data ??
yes
Sun bearOP
like if I send data to
fetch(api/teams/,{
method:"POST",
body:JSON.Stringify({somedata})
})
??
how would you change this trpc router to api route
get: protectedProcedure.query(async ({ ctx }) => {
const user = await ctx.prisma.user.findUnique({
where: { id: ctx.session.user.id },
include: {
teams: {
select: {
team: { select: { id: true, name: true, slug: true } },
role: true,
},
},
},
});

return user;
})
use await req.json()
and you have to parse the type to make prisma happy
because req.json() return Promise<any>
Sun bearOP
why dynamic route
export async function GET(req: NextRequest) {
  const session = await getSession();
  if (!session) {
    return NextResponse.json({ error: "not authorized" }, { status: 401 });
  }

  return prisma.user.findUnique({
    where: { id: session.user.id },
    include: {
      teams: {
        select: {
          team: { select: { id: true, name: true, slug: true } },
          role: true,
        },
      },
    },
  });
}
Sun bearOP
what about the ctx ?
there is no ctx
Sun bearOP
and protectedProcedure
just import what you need
this is why trpc popular lol
Sun bearOP
oh god so there no way around
yes you have, just do the work yourself
trpc make your life easily
Sun bearOP
what about the input
Sun bearOP
yeah my bad
you have to do the validation yourself
Sun bearOP
do I have to use middleware
do you mean middleware.ts?
Sun bearOP
yeah
I don't think you need for api
@Sun bear why dynamic route
Sun bearOP
?
because I dont know how your query look like
you can use static if you don't need
Sun bearOP
okay
thanks for the help
good luck
Sun bearOP
okay
export async function GET(request: Request) {}

export async function HEAD(request: Request) {}

export async function POST(request: Request) {}

export async function PUT(request: Request) {}

export async function DELETE(request: Request) {}

export async function PATCH(request: Request) {}
you can export multiple action in a route if you need
@Sun bear how I call it in frontend this code
you can't call it in frontend but you can call prisma query inside a server component
Sun bearOP
@Ray Do you know how to setup prefetching on trpc using T3 stack app router ??
Barbary Lion
Hi @Ray i red this thread because i also considered moving away from trpc because it gives me no control over per request cache and some of my critical requests gets cached and all i can do is to set no cache globally on httpBatchedLink, I wrote about this in their discussion but so far no one gave me an answer https://github.com/trpc/trpc/discussions/5123, would you have an idea if this is possible to do? 🙂
Barbary Lion
thank you! 😄
with experimental_nextCacheLink, we can make the time-based revalidation query
await api.greeting.query({ text: 'from server2' }, { context: { revalidate: 10 } });
and we can revalidate the query in server action like this
await api.greeting.revalidate({ text: 'from server1' });
Sun bearOP
@Ray How can we prefetch on client or server component in app router that used to be prefetched in getServerSideProps in page router ?
export const getServerSideProps: GetServerSideProps = async (context) => {
  const { req, res } = context;
  const ssg = await createSSG({ req, res });

  await ssg.teams.get.prefetch();
  await ssg.user.get.prefetch();
  const slug = TeamRouteQueryType.parse(context.query).team;

  // pass team into this promise for ssg prefetch of different team-based routes
  await Promise.allSettled([
    ssg.teams.getApiKey.prefetch({
      slug: slug,
    }),
  ]);

  return {
    props: {
      trpcState: ssg.dehydrate(),
    },
  };
};
Barbary Lion
thanks @Ray ! you rock! Thats going to make my life better 🙂
Barbary Lion
one more think, where do you found info about this experimental feature? I can't find anything in their docs? And do you use react query? I wanted to save on a bundle size and i try to work thinks out the. way i get data in rsc and on client i only do websocket connection and react query does not work with websockets but maybe you would advise something else? Because sometimes i feel like calling my trpc backend from client would give better ux and
im not sure if im not just being stubborn and counterproductive ;p And again, where do i find experimental features to follow what good is comming? ? 🙂
but in app router, I don't see the need of react-query yet
Barbary Lion
okay, thanks a lot 🙂 super thanks!