Skip to content
Source
Sign inSign up
TanStack/router

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

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

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

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

  2. 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!")
      });
    }
  3. 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!

  4. 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 in to join this conversation.