Can't redirect in server functions with middleware #4460
Send to my agentWhich project does this relate to?#
Start
Describe the bug#
Throwing redirects in server functions that use middleware doesn't work. It works fine if I remove the middleware. I am using the useServerFn() helper hook on the client.
The problem seems to be that the isRedirect() helper from @tanstack/router-core expects the response to be a type of Response with an options prop.
When using middleware, the response is a plain object.
Your Example Website or App#
https://codesandbox.io/p/devbox/thirsty-gould-yc3fks
Steps to Reproduce the Bug or Issue#
- Click the button "With middleware (not working)" - notice no redirect
- Click the button "Without middleware (working)" - you get redirected to the /posts page
Expected behavior#
I expect that redirects within server functions work regardless of whether I use middleware or not.
Screenshots or Videos#
No response
Platform#
I believe it is platform agnostic.
Additional context#
No response
It might be easier to extend the
useServerFnhook to cater for middleware responses and perform the redirect if applicable.I encountered the same issue. I resolved it by temporarily creating a global middleware.
Here's the middleware code I used:
// src/global-middleware.ts import { isRedirect } from '@tanstack/react-router' import { createMiddleware, registerGlobalMiddleware, } from '@tanstack/react-start' const convertRedirectErrorToExceptionMiddleware = createMiddleware({ type: 'function', }).server(async ({ next }) => { const result = await next() if ('error' in result && isRedirect(result.error)) { throw result.error } return result }) registerGlobalMiddleware({ middleware: [convertRedirectErrorToExceptionMiddleware], })Remember to import this file where needed.
// src/router.ts import { createRouter as createTanStackRouter } from '@tanstack/react-router' import { routeTree } from './routeTree.gen' import { DefaultCatchBoundary } from './components/DefaultCatchBoundary' import { NotFound } from './components/NotFound' import './global-middleware' export function createRouter() { const router = createTanStackRouter({ routeTree, defaultPreload: 'intent', defaultErrorComponent: DefaultCatchBoundary, defaultNotFoundComponent: () => <NotFound />, scrollRestoration: true, }) return router }It seems that redirects work when using them in Route.loader functions. Global middleware doesn't work on some platforms as stated here https://github.com/TanStack/router/issues/3869
This is still ongoing... Is this normal behavior ? Should we only use redirect in loaders and not middleware ?
can you please check if this still exists on the latest version?
It still exists on RC yes, only when using the solution of JsonKim above then it works (re-throwing the error ourselves in another middleware)
After the RC announcement, I tested again to see if the issue was resolved, but it’s still occurring.
schiller-manuel(GitHub profile, opens in a new tab) added labelsneeded-for-start-stable
The temporary workaround provided by @JsonKim still seems to work on RC
// https://github.com/TanStack/router/issues/4460#issuecomment-3015836376 const convertRedirectErrorToExceptionMiddleware = createMiddleware({ type: 'function', }).server(async ({ next }) => { const result = await next() if ('error' in result && isRedirect(result.error)) { // eslint-disable-next-line @typescript-eslint/only-throw-error throw result.error } return result }) export const startInstance = createStart(() => ({ functionMiddleware: [convertRedirectErrorToExceptionMiddleware], requestMiddleware: [sessionMiddleware], }))Would it make sense if Start added this ☝️ type of middleware as a global function middleware by default?
In the
executeMiddlewarefunction of thecreateServerFn.tsfile instart-client-corethere are those lines:// ... if (middlewareFn) { // Execute the middleware return applyMiddleware(middlewareFn, ctx, async (newCtx) => { return next(newCtx).catch((error: any) => { // ---- Commenting the 6 lines below solve the "problem" ---------------- if (isRedirect(error) || isNotFound(error)) { return { ...newCtx, error, } } // -------------------------------------------------------------------- throw error }) }) } // ...It make the redirect and notFound not throw, which is what we would want so it can be picked up by the router lifecycle. I guess if it exists there is a reason tho lol.
for me the redirect was not working for server function, middleware, both, checked the docs ,
it mentioned that the redirect function can be used from beforeload, loader. no mention of server function etc.
I'm not that experienced, only thing I can do for now is to return a object and handle the navigation/redirect on the client side.
if anyone has any suggestions for me, I wanna know.
I had the same issue with redirect, the @JsonKim solves the redirect issue in middleware and server function. Hopefully maintainers can solve this issue to ensure it's working properly.
Tested the newest release, I confirm that redirects with middleware work correctly now.
Sign in to join this conversation.
I analyzed this problem and found the root cause. This touches core middleware mechanics, so I think it would be better if one of the maintainers fixed it
Here is the problem:
In
createServerFnyou start middleware chain by calling thenextfunctionIf there is no middleware, then this calls the base middleware that calls the server function. It doesn't catch any errors, so if you throw a redirect, it gets propagated to
useServerFn.if you have middlewares then you enter this branch in
createServerFnHere you have a catch handler and you transform the Error to a plain error object. This error object is propagated to useServerFn but is not recognized as a RedirectError. In general, the code expects a response object on redirect error.
I assume you want to not break the chain of middlewares on special errors like Redirect, so we have the following problems:
- Different handling for one (you treat the server function as base middleware) vs. many middlewares
I hope this helps you somehow @schiller-manuel