T
TanStack•5mo ago
passive-yellow

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,
})
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' })
}
if (error.code === 'UNAUTHORIZED') {
// here
throw redirect({ to: '/auth/sign-in' })
}
6 Replies
compatible-crimson
compatible-crimson•5mo ago
dont throw a redirect, use router.navigate() instead redirects are only properly handled in router lifecycle methods such as loader / beforeLoad and if you wrap a function in useServerFn
passive-yellow
passive-yellowOP•5mo ago
Thank you for getting back to me Manuel! Really appreciate it. I am a bit confused though, isn't router.navigate() reserved for the client by using the useRouter() hook? Is there another router I can import in an API route?
compatible-crimson
compatible-crimson•5mo ago
oh sorry thats on the server? so right now you cant throw a redirect in an API route
passive-yellow
passive-yellowOP•5mo ago
Yeah, it's within the api.trpc.$.tsx file
compatible-crimson
compatible-crimson•5mo ago
you would need to return a Response throwing a redirect threre will be possible soon however, but right now it is not yet possible
passive-yellow
passive-yellowOP•5mo ago
Alright, I will return an old school Response then 🙂 Thanks!

Did you find this page helpful?