Return TRPC Error from NextJS middleware
I am using trpc for my app's api but Im using NextJS middleware + upstash ratelimitting for.... well ratelimitting. Is there a way return a TRPC error from the middleware route?
26 Replies
Bump?
Throw it and use an error formatter
well in the nextjs middleware i can't really throw it. i could superjson the error and res.send() it. would that work?
@Tom How did you get on with this? and how were you able to run tRPC in the middleware?
I am currently trying to redirect if a user is not authenticated in nextjs middleware
Something like this:
but i keep getting the error :
Invariant: headers() expects to have requestAsyncStorage, none available.
To be honest, I never got a great answer. So I just manually worked around it on the client side. So if I ever got a json error from my service I assume it was the middleware rejecting it
I got advised today to do a simple fetch() query to the tRPC endpoint. The code snippet above i shared did not work at all
Why use NextJS middleware and not t.middleware?
@MarvinKR Because in my case I want to redirect the user when they become unauthenticated
Canβt you redirect inside tRPC?
Apparently not unless I am missing something?
Isnβt trpc doing fetch requests under the hood? So a redirect would not work.
you're correct
this looks good to me
I couldn't get the above to work.
seems to be something with client setup
I am using App Router with NextJS 14 - Monorepo but with separated server and client
This works: But i don't like that it will do an extra API call on every request.
can you show me your
experimental_createTRPCNextAppDirServer
-setup?
i have an idea
or like show me where const api
is defined
Ive been switching between
createTRPCProxyClient
and experimental_createTRPCNextAppDirServer
see above
so something like this maybe
& this becomes something like
I can test this.
basically override on demand for middlewares
Thank you very much for helping
the underlying issue seems to be that you can't call
headers()
in middlewaresAm i likely to be able to get the customLink to work?
That way i wouldn't be doing an extra API call on every request
perhaps, i'm not sure
@Alex / KATT π±
Edit: Your solution works. At first it was not entering the catch, but that was my fault.
btw your solution did solve another issue for me though: I was intermittently getting
Error: Invariant: headers() expects to have requestAsyncStorage,
in some route page.tsx
@Alex / KATT π± - Actually had to make some changes but it worked in the end:
nice, glad it worked out!
@Alex / KATT π± I think this might be interfereing with POST requests / mutations as there is a content-length mismatch. If you have a quick fix by better understanding that would be helpful. I am working on it now though
Yes i am having to do this to get it to work
seems messy
also not sure what changed. but now a simple
seems to work