Skip to content
Source
Sign inSign up
TanStack/router

Start: global request middleware is executed multiple times for single request #5239

Send to my agent
Closedandybons(GitHub profile, opens in a new tab) opened this issue 1 comment

Which project does this relate to?

Start

Describe the bug

When global middleware is registered per the instructions in https://tanstack.com/start/latest/docs/framework/react/middleware#global-request-middleware and referenced by server function, it ends up being executed multiple times.

Your Example Website or App

https://codesandbox.io/p/devbox/elated-ioana-8mjsp4

Steps to Reproduce the Bug or Issue

  1. Add a middleware function to the request middleware in start.ts:
export const loggingMiddleware = createMiddleware().server(async ({ next }) => {
  const request = getRequest();
  console.log("request", request.url, crypto.randomUUID());
  return next();
});

export const startInstance = createStart(() => {
  return {
    requestMiddleware: [loggingMiddleware],
  };
});
  1. reference that middleware in a serverfn:
export const serverFn = createServerFn()
  .middleware([loggingMiddleware])
  .handler(async () => {
    return { foo: "bar" };
  });
  1. Call that serverfn in a beforeLoad context and fully reload the page
  2. Notice that three requests are logged with the same request url

Expected behavior

I expect a single log per request url

Screenshots or Videos

No response

Platform

  • Router / Start Version: 1.132.7

Additional context

No response

  1. Based on my experience it's not even related to global middleware or request middleware. Even standard server function middleware is called two times during single server function call.

    What I noticed additionally is that it only happens during SSR request. When server function is called from client, middleware is correctly called only once.

    Adding following code to app created using npm create @tanstack/start@latest:

    const middleware = createMiddleware({ type: "function" }).server(
      async ({ next, functionId }) => {
        console.log("middleware -> ", functionId);
        return next();
      },
    );
    
    export const getPunkSongs = createServerFn({
      method: "GET",
    })
      .middleware([middleware])
      .handler(async () => {
        console.log("getPunkSongs");
        return [];
      });

    causes following output during SSR

    middleware ->  src_data_demo_punk-songs_ts--getPunkSongs_createServerFn_handler
    middleware ->  src_data_demo_punk-songs_ts--getPunkSongs_createServerFn_handler
    getPunkSongs

    and during client navigation

    middleware ->  src_data_demo_punk-songs_ts--getPunkSongs_createServerFn_handler
    getPunkSongs
  2. schiller-manuel(GitHub profile, opens in a new tab) added labelsneeded-for-start-stable

Sign in to join this conversation.