tRPC, NextJS 14, createTRPCProxyClient, How can I globally manage errors?
I want to be able to redirect a user when they become unauthenticated. Someone else mentioned to create some NextJS middleware which makes an api call for the user but then that will make an extra API call for every tRPC request. It feels like there should be someway I can centrally manage errors where if tRPC returns an 'UNAUTHORIZED' error for any procedure I can do a redirect to '/login'
I have a monorepo with everything together but the apps will be deployed separately eventually.
10 Replies
I have been trying with a custom link like below. But the redirect does not seem to run.
i think its because the error is still being 'thrown'
Thanks @Dani; Let me test!
is
navigate
coming from useNavigate
Because then it will need to be client sideI'm using
react-router-dom
, it's an SPA in my case; you can just replace with whatever redirect function next.js provides youah damn
i cant use hooks as this is server side only
Unsure if anything else is needed if you do SSR, haven't worked with next.js in a while
ah
ive tried loads now and cant find a good solution
In your initial snippet you were importing redirect, can't you just use that?
so just replace
navigate
with redirect
yeah it just doesn't work
something to do with observables i think
someone on the next support forum just said
redirect will only work if next can catch the error
thanks for your help thoughUnfortunate; hopefully someone else has a solution
Well I manage everything from the main layout file, usually, I haven't found anything better, this for Vite or Next. This allows me to centralize the app a bit (besides redux). You can also use redux and have a error state or something, there are many ways to globally manage errors.
Hi @Pablo M, thanks for sharing. Could you share a snippet of your layout file