Type errors chaining middleware together.
In the docs, it suggests you can chain middleware together while building up state in context. But in this case, the context is not typed unlike the majority of Start because the middleware can be used in different spots.
Maybe we should add an explicit typing for the context that each middleware supports?
Something like createMiddleware().context( z.object( { authUser: AuthUser.optional() } ).passthrough() ).validator(.....).server(...)
So that one can put in compile time guarantees on the context required. I believe it would get rid of the type errors in the middleware functions and also validate you combined multiple middlewares correctly in a server function. Bomb.
FYI: I'm using TanStack/Start+Router v1.120.13.


7 Replies
rival-blackOP•3mo ago
I have backed out my attempt to chaining together middleware that depends on context state passing for now. But it is weird that the docs suggest it when it just results in type errors in practice: https://tanstack.com/start/latest/docs/framework/react/middleware#providing-context-to-the-next-middleware-via-next
automatic-azure•3mo ago
It's not a type error, it's just a specific example that was included.
automatic-azure•3mo ago
Middleware | TanStack Start React Docs
What is Server Function Middleware? Middleware allows you to customize the behavior of server functions created with createServerFn with things like shared validation, context, and much more. Middlewa...
automatic-azure•3mo ago
`
const loggingMiddleware = createMiddleware({ type: "function" })
.middleware([awesomeMiddleware])
.server(async ({ next, context }) => {
console.log("Is awesome?", context.isAwesome);
return next();
});`
You have to wrap an additional middleware method before that to be able to get the standard context typesrival-blackOP•3mo ago
That makes sense. So the docs were incorrect then. I get it now. You chain the middleware explicitly in each new middleware.
Thank you!
automatic-azure•3mo ago
Your welcome
adverse-sapphire•3mo ago
PR to the docs always welcome!