Closed Q16solver closed 1 year ago
This would be great. Currently doing this by try
catch
ing every client query and handling the errors in one function
I believe this can be achieved by adding a TRPC middle-ware to check session for every request and you can return unauthorized
error. Or I am missing something?
export const privateProcedure = publicProcedure.use(async ({
ctx,
next,
}) => {
if (!ctx.user) {
throw new TRPCError({
code: 'UNAUTHORIZED',
})
}
return next({
ctx,
})
},
)
For more information: https://github.com/wobsoriano/trpc-nuxt/issues/69#issuecomment-1428194619
@mubaidr The issue isn't to do with returning the error from the backend, it's more of a frontend issue of trying to redirect routes once trpc realises it's an unauthorised request. Curremtly there's no way to do that, although I'm not sure if it's because of upstream trpc package not providing that functionality to intercept requests like axios in the frontend
Oh ok, but regarding the request intercepting TRPC has links
: https://trpc.io/docs/links
That does seem like a possible solution though it doesn’t seem like it will be simple and don’t see any standards for doing it, at least for nuxt side, I’ll have a look and see if it’s possible to use navigateTo as some errorLink
Error links works like a charm, just follow the trpc links docs and add a navigateTo on error, for anyone who is wondering how to do it. Closing this issue.
@Q16solver Can you please sample code?
Hello!
I wanted to do something similar to the pic below, but wasn't sure if that was currently possible since navigateTo doesn't exist inside the onError function. This should be something that's done like the axios interceptor where I check the code to see if it's 401 (unauthorised) or 403 (forbidden) then redirect user to login page. Was wondering if it's currently supported since I couldn't find any docs for nuxt api handler nor the links part and I think those are the only places where this seems reasonable. Other places like middleware don't seem to be the correct places to do this.