How do you globally handle auth errors for tRPC Procedures in Server Components (clean cookies & red
I'm using Next.js App Router with a standalone tRPC server, and I'm hitting a wall with authentication error handling in Server Components.
Goal: I want to catch 401 errors from my tRPC procedures called in server components, clear cookies, and redirect the user to the login page — globally and cleanly.
What I Tried
The only working (but messy) approach I found is to wrap every Server Component in a try/catch block and run the logout logic manually. It is so easy to forget just one place and have error months later.
I also tried using a custom link on the trpcServer client to catch errors, but that’s not viable because -
You can’t redirect or mutate cookies (cookies() API) from a link because it is not inside a Server Component.
Architecture Notes
- Next.js App with app/ router.
- Standalone tRPC server (not co-located).
- tRPC procedures call a legacy PHP backend, and I forward HTTP statuses to the tRPC responses.
-
/trpc/[trpc]
route is used by trpc client and "forward" the trpc call to the standalone TRPC.
- The trpcServer client is a TRPCProxyClient that talks to the standalone server.
My Question
How do you globally handle 401s in Server Components in a clean way (without wrapping every call)?
Is my architecture fundamentally limiting this pattern? Would you restructure it?
I’m open to feedback, patterns, or even architectural suggestions to get out of this mess.
Thanks0 Replies