wobsoriano / trpc-nuxt

End-to-end typesafe APIs in Nuxt applications.
trpc-nuxt.vercel.app
MIT License
675 stars 38 forks source link

[Question]: Is it possible to have global error handling for redirecting unauthorised requests? #59

Closed Q16solver closed 1 year ago

Q16solver commented 1 year ago

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.

image

huzaifahj commented 1 year ago

This would be great. Currently doing this by try catching every client query and handling the errors in one function

mubaidr commented 1 year ago

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

Q16solver commented 1 year ago

@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

mubaidr commented 1 year ago

Oh ok, but regarding the request intercepting TRPC has links: https://trpc.io/docs/links

Q16solver commented 1 year ago

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

Q16solver commented 1 year ago

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.

mubaidr commented 1 year ago

@Q16solver Can you please sample code?

Q16solver commented 1 year ago

@mubaidr https://github.com/Esposter/Esposter/blob/main/services/trpc/errorLink.ts https://github.com/Esposter/Esposter/blob/main/packages/app/services/trpc/errorLink.ts

birdlavv commented 20 hours ago

Fixed link https://github.com/Esposter/Esposter/blob/main/packages/app/services/trpc/errorLink.ts