Loading...
Loading...
createMiddleware, request middleware (.server only), server function middleware (.client + .server), context passing via next({ context }), sendContext for client-server transfer, global middleware via createStart in src/start.ts, middleware factories, method order enforcement, fetch override precedence.
npx skill4agent add tanstack/router middlewareCRITICAL: TypeScript enforces method order:→middleware()→validator()→client(). Wrong order causes type errors. CRITICAL: Validating the shape ofserver()(e.g.sendContext) is NOT authorization. A parsed identifier is a well-formed identifier, not an authorized one. Always re-check access against the session principal before using a client-sent ID as a query key, filter, or path parameter.z.string().uuid().parse(...)
| Feature | Request Middleware | Server Function Middleware |
|---|---|---|
| Scope | All server requests (SSR, routes, functions) | Server functions only |
| Methods | | |
| Input validation | No | Yes ( |
| Client-side logic | No | Yes |
| Created with | | |
// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createMiddleware } from '@tanstack/react-start'
const loggingMiddleware = createMiddleware().server(
async ({ next, context, request }) => {
console.log('Request:', request.url)
const result = await next()
return result
},
)// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createMiddleware } from '@tanstack/react-start'
const authMiddleware = createMiddleware({ type: 'function' })
.client(async ({ next }) => {
// Runs on client BEFORE the RPC call
const result = await next()
// Runs on client AFTER the RPC response
return result
})
.server(async ({ next, context }) => {
// Runs on server BEFORE the handler
const result = await next()
// Runs on server AFTER the handler
return result
})// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createServerFn } from '@tanstack/react-start'
const fn = createServerFn()
.middleware([authMiddleware])
.handler(async ({ context }) => {
// context contains data from middleware
return { user: context.user }
})const authMiddleware = createMiddleware().server(async ({ next, request }) => {
const session = await getSession(request.headers)
if (!session) throw new Error('Unauthorized')
return next({
context: { session },
})
})
const roleMiddleware = createMiddleware()
.middleware([authMiddleware])
.server(async ({ next, context }) => {
console.log('Session:', context.session) // typed!
return next()
})const workspaceMiddleware = createMiddleware({ type: 'function' })
.client(async ({ next, context }) => {
return next({
sendContext: {
workspaceId: context.workspaceId,
},
})
})
.server(async ({ next, context }) => {
// workspaceId available here, but VALIDATE IT
console.log('Workspace:', context.workspaceId)
return next()
})const serverTimer = createMiddleware({ type: 'function' }).server(
async ({ next }) => {
return next({
sendContext: {
timeFromServer: new Date(),
},
})
},
)
const clientLogger = createMiddleware({ type: 'function' })
.middleware([serverTimer])
.client(async ({ next }) => {
const result = await next()
console.log('Server time:', result.context.timeFromServer)
return result
})import { z } from 'zod'
import { zodValidator } from '@tanstack/zod-adapter'
const workspaceMiddleware = createMiddleware({ type: 'function' })
.validator(zodValidator(z.object({ workspaceId: z.string() })))
.server(async ({ next, data }) => {
console.log('Workspace:', data.workspaceId)
return next()
})src/start.ts// src/start.ts
// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import { createStart, createMiddleware } from '@tanstack/react-start'
const requestLogger = createMiddleware().server(async ({ next, request }) => {
console.log(`${request.method} ${request.url}`)
return next()
})
const functionAuth = createMiddleware({ type: 'function' }).server(
async ({ next }) => {
// runs for every server function
return next()
},
)
export const startInstance = createStart(() => ({
requestMiddleware: [requestLogger],
functionMiddleware: [functionAuth],
}))export const Route = createFileRoute('/api/users')({
server: {
middleware: [authMiddleware],
handlers: {
GET: async ({ context }) => Response.json(context.user),
POST: async ({ request }) => {
/* ... */
},
},
},
})export const Route = createFileRoute('/api/users')({
server: {
handlers: ({ createHandlers }) =>
createHandlers({
GET: async () => Response.json({ public: true }),
POST: {
middleware: [authMiddleware],
handler: async ({ context }) => {
return Response.json({ user: context.session.user })
},
},
}),
},
})const authMiddleware = createMiddleware().server(async ({ next, request }) => {
const session = await auth.getSession({ headers: request.headers })
if (!session) throw new Error('Unauthorized')
return next({ context: { session } })
})Attachto everyauthMiddlewarethat needs auth. Server functions are API endpoints; a routecreateServerFndoes not protect their data, only the route's UI. Protect the endpoint that reads or mutates private data. See router-core/auth-and-guards and start-core/auth-server-primitives.beforeLoad
type Permissions = Record<string, string[]>
function authorizationMiddleware(permissions: Permissions) {
return createMiddleware({ type: 'function' })
.middleware([authMiddleware])
.server(async ({ next, context }) => {
const granted = await auth.hasPermission(context.session, permissions)
if (!granted) throw new Error('Forbidden')
return next()
})
}
// Usage
const getClients = createServerFn()
.middleware([authorizationMiddleware({ client: ['read'] })])
.handler(async () => {
return { message: 'The user can read clients.' }
})const authMiddleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
return next({
headers: { Authorization: `Bearer ${getToken()}` },
})
},
)// Use @tanstack/<framework>-start for your framework (react, solid, vue)
import type { CustomFetch } from '@tanstack/react-start'
const loggingMiddleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
const customFetch: CustomFetch = async (url, init) => {
console.log('Request:', url)
return fetch(url, init)
}
return next({ fetch: customFetch })
},
)sendContext.server(async ({ next, context }) => {
// SQL-injectable AND tenant-walkable
await db.query(`SELECT * FROM workspace_${context.workspaceId}`)
return next()
}).server(async ({ next, context }) => {
// Looks safe, isn't. UUID is well-formed but the user may not be a member.
const workspaceId = z.string().uuid().parse(context.workspaceId)
await db.query('SELECT * FROM workspaces WHERE id = $1', [workspaceId])
return next()
}).middleware([authMiddleware]) // session loaded from cookie, NOT from sendContext
.server(async ({ next, context }) => {
const workspaceId = z.string().uuid().parse(context.workspaceId)
// Verify the session principal can access this workspace.
const member = await db.memberships.find({
userId: context.session.userId,
workspaceId,
})
if (!member) throw new Error('Not a member of this workspace')
await db.query('SELECT * FROM workspaces WHERE id = $1', [workspaceId])
return next({ context: { workspaceId } })
})authMiddlewaresendContextcreateServerFn.client().client()localStoragewindowReferenceError// WRONG — localStorage doesn't exist on the server during SSR
const middleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
const token = localStorage.getItem('token')
return next({ sendContext: { token } })
},
)
// CORRECT — use cookies/headers or guard with typeof window check
const middleware = createMiddleware({ type: 'function' }).client(
async ({ next }) => {
const token =
typeof window !== 'undefined' ? localStorage.getItem('token') : null
return next({ sendContext: { token } })
},
)// WRONG — type error
createMiddleware({ type: 'function' })
.server(() => { ... })
.client(() => { ... })
// CORRECT — middleware → validator → client → server
createMiddleware({ type: 'function' })
.middleware([dep])
.validator(schema)
.client(({ next }) => next())
.server(({ next }) => next())authMiddleware