Skip to content

Global Middleware causes serialisation error when throwing redirects via server function #5372

Closed

Description

@mubrik

Which project does this relate to?

Start

Describe the bug

When there is a global function middleware present in the start instance created in a start.ts file, and a redirect is thrown by any server function a SerovalUnsupportedTypeError occurs.

Your Example Website or App

https://github.com/mubrik/tanstack-start-middleware-issue

Steps to Reproduce the Bug or Issue

start of using the basic install steps:

npx gitpick TanStack/router/tree/main/examples/react/start-basic start-basic
cd start-basic
npm install
npm run dev

create a start.ts file in the src directory, content:

import { createMiddleware, createStart } from '@tanstack/react-start'

export const fnMw = createMiddleware({ type: 'function' })
  .server(({ next }) => {
    console.log("herrr")
    return next({
      context: {
        fromFnMw: true,
      },
    })
  })

export const startInstance = createStart(() => {
  return {
    defaultSsr: true,
    functionMiddleware: [fnMw],
  }
})

update vite config to match:

export default defineConfig({
  server: {
    port: 3000,
  },
  plugins: [
    tsConfigPaths({
      projects: ['./tsconfig.json'],
    }),
    tanstackStart({
      srcDirectory: 'src',
      start: { entry: './start.ts' },
    }),
    viteReact(),
  ],
})

Add a file with the server function throwing redirect:

import { createServerFn } from '@tanstack/react-start';
import { redirect } from '@tanstack/react-router';

export const redirectTest = createServerFn()
    .handler(async () => {
        throw redirect({ to: "/posts" })
    })

// in a component 
function Home() {
  const redir = useServerFn(redirectTest);

  return (
    <div className="p-2">
      <h3>Welcome Home!!!</h3>
      <button onClick={() => redir()}>test redirect</button>
    </div>
  )
}

Expected behavior

I expected the redirect to be propagated to the client router correctly

Screenshots or Videos

Image

Platform

  • Router / Start Version: 1.132.38
  • OS: macOS
  • Browser: Chrome
  • Browser Version: 138
  • Bundler: vite
  • Bundler Version: 7.1.1

Additional context

No response

Activity

  1. kylekz commented on Oct 20, 2025

    @kylekz
    Contributor

    also seeing this using just a server function middleware attached with .middleware([myMiddleware]) rather than a global middleware, if it matters

    export const authMiddleware = createMiddleware({ type: "function" }).server(
      async ({ next }) => {
        const session = await auth.api.getSession({
          headers: getRequestHeaders(),
        });
    
        return next({
          context: {
            session,
          },
        });
      },
    );
    
    export const myFunction = createServerFn({ method: "POST" })
      .inputValidator(someSchema)
      .middleware([authMiddleware])
      .handler(async ({ data, context }) => {
        throw redirect({ to: '/' });
      });
    
    function useMyMutation() {
      const mutationFn = useServerFn(myFunction);
      return useMutation({
        mutationFn,
        onSuccess: () => toast.success("Success!")
      });
    }
  2. willhoney7 commented on Nov 3, 2025

    @willhoney7

    Same, also seeing this issue with a normal server function and [non global] middleware. This one is a bit problematic for us and will block our migration over to tanstack/start. Hoping it can be addressed in the next few weeks as stable v1 gets closer. Thanks team!

  3. willhoney7 commented on Nov 10, 2025

    @willhoney7

    Found a workaround via discord

    import { isRedirect } from "@tanstack/react-router";
    import { createMiddleware, createStart } from "@tanstack/react-start";
    
    const tempRedirectMiddleware = createMiddleware({ type: "function" }).server(async ({ next }) => {
      const result = await next();
      if ("error" in result && isRedirect(result.error)) {
        throw result.error;
      }
      return result;
    });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions