router icon indicating copy to clipboard operation
router copied to clipboard

registerGlobalMiddleware has no effect.

Open rtrampox opened this issue 8 months ago • 17 comments

Which project does this relate to?

Start

Describe the bug

middlewares added globally with registerGlobalMiddleware never run.

Your Example Website or App

https://stackblitz.com/github/tanstack/router/tree/main/examples/react/start-basic?file=src%2Fglobal-middleware.ts

Steps to Reproduce the Bug or Issue

  1. Go to stackblitz example.
  2. Test with anything that invokes a server function.
  3. See that the logger middleware never runs, and nothing is logged to the console.

Expected behavior

The logger middleware is expected to output to the console, but nothing is being showed.

Screenshots or Videos

No response

Platform

  • OS: Windows, and Linux
  • Browser: Edge
  • Version: 134.0

Additional context

No response

rtrampox avatar Mar 27 '25 11:03 rtrampox

What is weird, on my mac it works as intended, but on windows it does nothing

EliasGit117 avatar Apr 10 '25 19:04 EliasGit117

What is weird, on my mac it works as intended, but on windows it does nothing

It worked once in a stackblitz container, and then I tried my codebase, and nothing. Even inside a docker container.

rtrampox avatar Apr 10 '25 19:04 rtrampox

The same template and problem. I even added throw new Error("test") to the file and it didn't cause the program to crash. It seems that the file is not executed at all.

1adybug avatar Apr 11 '25 08:04 1adybug

On server with linux also everything works as intended, so I assume it could be only windows node problem

EliasGit117 avatar Apr 11 '25 09:04 EliasGit117

maybe a case sensitivity issue?

schiller-manuel avatar Apr 11 '25 09:04 schiller-manuel

maybe a case sensitivity issue?

Didn't get you

EliasGit117 avatar Apr 11 '25 09:04 EliasGit117

just thought how windows and Linux/Mac differ. and one difference is whether the file system is case sensitive or not.

schiller-manuel avatar Apr 11 '25 10:04 schiller-manuel

just thought how windows and Linux/Mac differ. and one difference is whether the file system is case sensitive or not.

If it's Windows related, it's probably an issue with the backslashes

rtrampox avatar Apr 11 '25 14:04 rtrampox

I am also having a similar situation.

akawahuynh avatar Apr 17 '25 04:04 akawahuynh

I am also having a similar situation.

jin-benben avatar Apr 23 '25 03:04 jin-benben

It's at least partly related to slashes.

https://github.com/TanStack/router/blob/8edeeaa6a13aab67211299e8cf38cf5f3533d123/packages/react-start-plugin/src/index.ts#L56-L62

It fails on this check because they use different slashes.

id.includes(entry)
id ~/src/client.tsx
entry ~\src\client.tsx

Windows 11, Node 22.13.0

nr1brolyfan avatar Apr 25 '25 19:04 nr1brolyfan

Do not forget : global middlewares are ONLY used with serverFunction. Global middlewares are not called globally in your application when you are navigating.

GhostvOne avatar May 25 '25 05:05 GhostvOne

Steps to Reproduce the Bug or Issue

1. Go to [stackblitz example](https://stackblitz.com/github/tanstack/router/tree/main/examples/react/start-basic?file=src%2Fglobal-middleware.ts).

2. Test with anything that invokes a server function.

3. See that the logger middleware never runs, and nothing is logged to the console.

Do not forget : global middlewares are ONLY used with serverFunction. Global middlewares are not called globally in your application when you are navigating.

That's exactly whats written on the issue.

rtrampox avatar May 25 '25 17:05 rtrampox

Seeing a similar issue on my mac

Resolved - I had not put the file in the right place https://github.com/TanStack/router/pull/3501

danwoods avatar May 30 '25 20:05 danwoods

Same here, also on Windows

benny856694 avatar Jun 10 '25 07:06 benny856694

Still not working for me on windows 11

SpeedOfSpin avatar Jun 14 '25 15:06 SpeedOfSpin

For me it seems not to be working too. Mac OS sequoia. It can be a regression on the new version.

felipestanzani avatar Jun 17 '25 22:06 felipestanzani

Just wanted to mention that I'm running into this as well in my TanStack Start project.

I wanted to use global middleware to inject the authorization header like described here so that I can check the authorization header in server middleware that runs before a server function inside beforeLoad

// from https://tanstack.com/start/latest/docs/framework/react/middleware#modifying-the-client-request
import { getToken } from 'my-auth-library'

const authMiddleware = createMiddleware({ type: 'function' }).client(
  async ({ next }) => {
    return next({
      headers: {
        Authorization: `Bearer ${getToken()}`,
      },
    })
  },
)

But I couldn't get it to work properly using the global middleware. I also tried adding it before my server middleware but that didn't work when refreshing the current page.

// does not work when refreshing the page
export const getUserId = createServerFn({ method: 'GET' })
  .middleware([authMiddleware, serverAuthMiddleware])
  .handler(async ({ context }) => {
    return context?.user?.id
  })

EddyVinck avatar Jun 23 '25 10:06 EddyVinck

same here

TheOrdinaryWow avatar Jun 25 '25 03:06 TheOrdinaryWow

not working for me either

ZJTAN97 avatar Jul 10 '25 11:07 ZJTAN97

It might has being removed at some point but global-middleware.ts auto loading has being removed. It's still referenced in the docs but just placing that file would do nothing on the the whole flow.

Make sure that you are loading that file(or any other middleware file) explicitly so it runs.

de-tester avatar Jul 13 '25 20:07 de-tester

@schiller-manuel posted on Discord: "yes this is a known issue, we still need to implement global middlware registration now that devinxi has happened".

TahaBoulehmi avatar Jul 15 '25 13:07 TahaBoulehmi

Any updates on this? It should be warned in docs or remove it entirely. Lost an hour of my life.

juliomuhlbauer avatar Aug 06 '25 18:08 juliomuhlbauer

I just imported the global middleware in the server.tsx file and it seems to work quite well. This is with the latest version without vinxi.

SpeedOfSpin avatar Aug 08 '25 09:08 SpeedOfSpin

@SpeedOfSpin do you mind sharing some snippet?

leonardo2204 avatar Sep 02 '25 15:09 leonardo2204

Sure. On the latest tanstack start repo (the one without vinxi) You should have a server,ts file at the same level as your routeTree.gen.ts file. This is mine. You can see I just import my global-middleware file here.

server.ts

import { createStartHandler, defaultStreamHandler } from "@tanstack/react-start/server";
import { createRouter } from "./router";
import "@/global-middleware";

export default createStartHandler({
  createRouter,
})(defaultStreamHandler);

global-middleware.ts

import { registerGlobalMiddleware } from "@tanstack/react-start";
import { authMiddleware } from "./middleware/auth-middleware";
import { emitErrors } from "./middleware/emit-errors";

console.log("Registering global middleware");
registerGlobalMiddleware({
  middleware: [emitErrors, authMiddleware],
});

emit-errors.ts

import { createMiddleware } from "@tanstack/react-start";

export const emitErrors = createMiddleware({ type: "function" })
  .client(async ({ next }) => {
    try {
      const result = await next();
      return result;
    } catch (error: any) {
      if (typeof error?.message === "string") {
        const actualError = JSON.parse(error.message);
        window.dispatchEvent(new CustomEvent("server-error", { detail: actualError }));
      }
      throw error;
    }
  })
  .server(async ({ next }) => {
    try {
      const result = await next();
      return result;
    } catch (error: any) {
      console.error(error);
      throw error;
    }
  });

eriknodland avatar Sep 02 '25 15:09 eriknodland

Please update the docs. Trying to run npx create-start-app and setting global middleware according to the latest version of the docs does not work anymore.

Updating the docs should be a prerequisite to publishing any packages, especially starter repos as this is the point highest risk of churn from your project. It shows you are not serious and people will go back to next or RR.

grunklejp avatar Sep 03 '25 17:09 grunklejp

global middleware handling changed completely in RC. please see the docs https://tanstack.com/start/latest/docs/framework/react/middleware#global-middleware

schiller-manuel avatar Sep 23 '25 22:09 schiller-manuel

global middleware handling changed completely in RC. please see the docs https://tanstack.com/start/latest/docs/framework/react/middleware#global-middleware

Your link 404s and when I run @tanstack/start@latest with Sentry integration, it references registerGlobalMiddleware from the @tanstack/react-start which does not exist.

EverybodyKurts avatar Oct 28 '25 00:10 EverybodyKurts

@EverybodyKurts sorry about the link, please see https://tanstack.com/start/latest/docs/framework/react/guide/middleware#global-middleware

sentry integration is still being updated for RC so this won't work yet

schiller-manuel avatar Oct 28 '25 00:10 schiller-manuel