T
tRPC

❓-help

tRPC, NextJS 14, createTRPCProxyClient, How can I globally manage errors?

BBillyBob1/15/2024
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.
BBillyBob1/16/2024
I have been trying with a custom link like below. But the redirect does not seem to run.
import { redirect } from 'next/navigation'

export const customLink: TRPCLink<AppRouter> = () => {
return ({ next, op }) => {
return observable((observer) => {
const unsubscribe = next(op).subscribe({
next(value) {
observer.next(value)
},
error(err) {
observer.error(err)
if (err?.data?.code === 'UNAUTHORIZED') {
redirect('/login')
}
},
complete() {
observer.complete()
},
})
return unsubscribe
})
}
}
import { redirect } from 'next/navigation'

export const customLink: TRPCLink<AppRouter> = () => {
return ({ next, op }) => {
return observable((observer) => {
const unsubscribe = next(op).subscribe({
next(value) {
observer.next(value)
},
error(err) {
observer.error(err)
if (err?.data?.code === 'UNAUTHORIZED') {
redirect('/login')
}
},
complete() {
observer.complete()
},
})
return unsubscribe
})
}
}
i think its because the error is still being 'thrown'
DDani;1/17/2024
import { OperationLink, TRPCLink } from '@trpc/react-query';
import { observable, tap } from '@trpc/server/observable';

const errorLink: TRPCLink<AppRouter> = (): OperationLink<AppRouter> => {
const link: OperationLink<AppRouter> = ({ op, next }) => {
return observable((observer) => {
next(op)
.pipe(
tap({
error: (result) => {
if (result.data?.code === 'UNAUTHORIZED') {
navigate('/auth/login');
}
},
}),
)
.subscribe(observer);
});
};
return link;
};
import { OperationLink, TRPCLink } from '@trpc/react-query';
import { observable, tap } from '@trpc/server/observable';

const errorLink: TRPCLink<AppRouter> = (): OperationLink<AppRouter> => {
const link: OperationLink<AppRouter> = ({ op, next }) => {
return observable((observer) => {
next(op)
.pipe(
tap({
error: (result) => {
if (result.data?.code === 'UNAUTHORIZED') {
navigate('/auth/login');
}
},
}),
)
.subscribe(observer);
});
};
return link;
};
currently using this ^
BBillyBob1/17/2024
Thanks @Dani; Let me test! is navigate coming from useNavigate Because then it will need to be client side
DDani;1/17/2024
I'm using react-router-dom, it's an SPA in my case; you can just replace with whatever redirect function next.js provides you
BBillyBob1/17/2024
ah damn i cant use hooks as this is server side only
DDani;1/17/2024
Unsure if anything else is needed if you do SSR, haven't worked with next.js in a while ah
BBillyBob1/17/2024
ive tried loads now and cant find a good solution
DDani;1/17/2024
In your initial snippet you were importing redirect, can't you just use that?
import { redirect } from 'next/navigation'
import { redirect } from 'next/navigation'
so just replace navigate with redirect
BBillyBob1/17/2024
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 though
DDani;1/17/2024
Unfortunate; hopefully someone else has a solution
PMPablo M1/18/2024
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.
BBillyBob1/20/2024
Hi @Pablo M, thanks for sharing. Could you share a snippet of your layout file

Looking for more? Join the community!

Recommended Posts
next 14 setup errori got this type error after setting up trpc in next 14.0.4 Property 'createClient' does not exist No typesafety after migrating to 11?Not sure what happened when upgrading from 10 to 11. tried deleting node modules and lock file and ris there a way to send a streaming responseI'm not talking about batching multiple requests, but more of a one-way websocket-like channel betweError: Tried to access "$types.__endpoint" which is not available at runtimeHi all! I'm new here, so I hope i'm posting this in the right place. I'm trying to use tRPC using fitrpc output dates are typed as strings and not datesI'm using superjson as a transformer. When I query my data, it shows that fields that should be dateTRPC v10 to v11 - change logs locationWhere can I read the changlogs from v10 to v11? I have seen the migration guide, but no clear list tRPC won't return route with function, only JSONHey all, Why can I go to route 'test' and the 'This is a test!' is being returned, but when I try ttRPC router won't return, unless it's just json.Hey all, Why can I go to 'test' and the 'This is a test!' is being returned, but when I try to go tHow to make trpc output return strings and not datesI am **not** using superjson I would like for all of my trpc routes to return dates as strings. HowCannot read properties of undefined (reading 'input')login: trpc_1.publicProcedure.input(loginInput).mutation((opts) => __awaiter(void 0, void 0, void 0,Extending the client with "virtual" proceduresI'm hoping to write a virtual mutation which runs on the client and calls some other client-side apiDynamic Server Usage Error from RSC callsposted this on the create-t3-app server as well but not quite sure if the issue is T3 or TRPC relateNode 20, NPM: Send form values to DB with tRPC?Hey all, anyone in here with some tRPC experience? I have been going through YouTube video's and thGetting type error in v11 when trying to instantiate createTRPCQueryUtils```Type 'CreateTRPCReactBase<CreateRouterInner<RootConfig<{ ctx: object; meta: object; errorShape: DLoggerLink logging only via server logger in prodI have a logger link setup as declared in https://trpc.io/docs/client/links/loggerLink#usage ```ts Better error tracing when using TRPC routersHi, I'm using a trpc router and noticed that the error trace report is more or less non existent as client side Validation with ZODwill trpc validate input on the client before sending it to the server ?We're having some serious Intellisense performance issues with v10Hello. We have about ~30ish routers in `mergeRouters` (we're working on changing this to a namespaceParsing FormData on trpcHi all, I have function to put object on S3 const putObjectToS3 = async (body: FormData) => { ... }TRPC to connect a client app with a backend apigateway ?Hi everyone! Is it a good practice to use TRPC to connect my client application (Next.Js) with my b