Skip to content
Source
Sign inSign up
TanStack/router

Can't redirect in server functions with middleware #4460

Send to my agent
Closedjperasmus(GitHub profile, opens in a new tab) opened this issue 14 comments

Which 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

  1. Click the button "With middleware (not working)" - notice no redirect
  2. 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

  1. 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 createServerFn you start middleware chain by calling the next function

      // Start the middleware chain
      return next({
        ...opts,
        headers: opts.headers || {},
        sendContext: opts.sendContext || {},
        context: opts.context || {},
      })

    If 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 createServerFn

     if (middlewareFn) {
          // Execute the middleware
          return applyMiddleware(middlewareFn, ctx, async (newCtx) => {
            return next(newCtx).catch((error: any) => {
              if (isRedirect(error) || isNotFound(error)) {
                return {
                  ...newCtx,
                  error,
                }
              }
    
              throw error
            })
          })
        }

    Here 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

    • The logic to serialize and deserialize errors should be better. Redirect in router-core also expects a Response object

    I hope this helps you somehow @schiller-manuel

  2. It might be easier to extend the useServerFn hook to cater for middleware responses and perform the redirect if applicable.

  3. 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
    }
  4. 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

  5. This is still ongoing... Is this normal behavior ? Should we only use redirect in loaders and not middleware ?

  6. can you please check if this still exists on the latest version?

  7. 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)

  8. After the RC announcement, I tested again to see if the issue was resolved, but it’s still occurring.

  9. schiller-manuel(GitHub profile, opens in a new tab) added labelsneeded-for-start-stable

  10. 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],
    }))
  11. Would it make sense if Start added this ☝️ type of middleware as a global function middleware by default?

  12. In the executeMiddleware function of the createServerFn.ts file in start-client-core there 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.

  13. 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.

  14. 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.

  15. Tested the newest release, I confirm that redirects with middleware work correctly now.

Sign in to join this conversation.