[HOW TO?] Call trpc endpoints from vanilla nextJs api routes
Spinoff from an og thread here:
https://discordapp.com/channels/867764511159091230/1032301198990135347
HI! I am wanting to do the same thing...call a trpc route from within a nextjs public api endpoint.
I am using a fresh t3-turbo-with-clerk project which has trpc in packages/api (@acme/api)
here is my apps/nextjs/src/pages/api/post.ts file
10 Replies
i am getting a type error on
and when i load the page i get a json error:
Can someone assist me with the issue?
I know I could use https://github.com/jlalmes/trpc-openapi to expose routes, I just wanted to get a basic example working first and then look into that. I am only exposing routes atm for testing purposes
from what I can see, const caller = appRouter.createCaller({}); needs a ctx parameter.
my @acme/api/index.ts file has
Have you looked at our nextjs docs?
yes, i have been flipping through them all day
https://trpc.io/docs/server/server-side-calls#example-for-a-nextjs-api-endpoint
You shouldn't need createCaller
We have serverside helpers
Problem looks like you're not actually creating the necessary ctx object
but you shouldn't need to do it here
the documentation explains using createCaller for nextjs api endpoints via that link above. Why wouldnt I need it?
I have used the SSG helper in a pages/post/[id].tsx page, but didnt think that was the correct way to use it in an API route per the trpc documentation
Got it, I'm not really a user of next, but yes looks like we do recommend that in some situations
You'll need to call your createContext function
{} is not enough
ok, and in that function it expects some parameters (auth). However isnt the context object already set up inside @acme/api somewhere?
Here is my pages/dashboard page where I load the posts into a flashlist:
createContext is called by the adapter, but createCaller makes your calling code into the adapter
That first parameter is the context values
screens are located in packages/app/features (@acme/app) and here is the Homescreen linked from above file
trpc works fine on this page and loads the posts. Do i need to re-import clerk modules on pages/api/post to rebuild context?
i would think i could import context from @acme/api, then insert it into createCaller()
and yes i do believe context is the issue with my code because of the error:
but it is asking for ctx to have auth (clerk) and prisma, which id either have to import again or re-use from @acme/api
here is another github I have also been looking at:
https://github.com/trpc/trpc/issues/1724
this is code for the openapi generator that we should be able to pull some code from to assist. This is where I got the understanding that createCaller needs a ctx object and that ceateContext probably needs to be imported...but this is as far as I have got
so atm in my pages/api/posts.ts i have (shorted for brevity)
and I am still getting error