TanStackT
TanStack9mo ago
10 replies
cold-orange

redirect on error

Hello everyone.

I am trying to trigger a redirect to /auth/sign-in when the error code of tRPC is "UNAUTHORIZED"


import { createAPIFileRoute } from '@tanstack/react-start/api'
import { fetchRequestHandler } from '@trpc/server/adapters/fetch'
import { redirect } from '@tanstack/react-router'
import { appRouter } from '~/integrations/trpc/router'
import { createTRPCContext } from '~/integrations/trpc/config'

function handler({ request }: { request: Request }) {
  return fetchRequestHandler({
    req: request,
    router: appRouter,
    endpoint: '/api/trpc',
    createContext: () => createTRPCContext({ request }),
    onError: ({ error }) => {
      if (error.code === 'UNAUTHORIZED') {
        throw redirect({ to: '/auth/sign-in' })
      }
    },
  })
}

export const APIRoute = createAPIFileRoute('/api/trpc/$')({
  GET: handler,
  POST: handler,
})


However it does not redirect and shows an error boundary on the client.

Am I missing something here?


ps. I have verified that it's an actual UNAUTHORIZED code by checking if a console.log would fire here

if (error.code === 'UNAUTHORIZED') {
       // here
      throw redirect({ to: '/auth/sign-in' })
}
Was this page helpful?