MCPcopy Create free account
hub / github.com/TanStack/router / callNextMiddleware

Function callNextMiddleware

packages/start-client-core/src/createServerFn.ts:250–359  ·  view source on GitHub ↗
(ctx)

Source from the content-addressed store, hash-verified

248 }
249
250 const callNextMiddleware: NextFn = async (ctx) => {
251 // Get the next middleware
252 const nextMiddleware = flattenedMiddlewares.shift()
253
254 // If there are no more middlewares, return the context
255 if (!nextMiddleware) {
256 return ctx
257 }
258
259 // Execute the middleware
260 try {
261 let validator =
262 'validator' in nextMiddleware.options
263 ? nextMiddleware.options.validator
264 : undefined
265
266 // TODO remove upon stable
267 if (!validator && 'inputValidator' in nextMiddleware.options) {
268 validator = nextMiddleware.options.inputValidator
269 }
270
271 if (validator && env === 'server') {
272 // Execute the middleware's input function
273 ctx.data = await execValidator(validator as AnyValidator, ctx.data)
274 }
275
276 let middlewareFn: MiddlewareFn | undefined = undefined
277 if (env === 'client') {
278 if ('client' in nextMiddleware.options) {
279 middlewareFn = nextMiddleware.options.client as
280 | MiddlewareFn
281 | undefined
282 }
283 }
284 // env === 'server'
285 else if ('server' in nextMiddleware.options) {
286 middlewareFn = nextMiddleware.options.server as MiddlewareFn | undefined
287 }
288
289 if (middlewareFn) {
290 const userNext = async (
291 userCtx: ServerFnMiddlewareResult | undefined = {} as any,
292 ) => {
293 // Return the next middleware
294 // Use safeObjectMerge for context objects to prevent prototype pollution
295 const nextCtx = {
296 ...ctx,
297 ...userCtx,
298 context: safeObjectMerge(ctx.context, userCtx.context),
299 sendContext: safeObjectMerge(ctx.sendContext, userCtx.sendContext),
300 headers: mergeHeaders(ctx.headers, userCtx.headers),
301 _callSiteFetch: ctx._callSiteFetch,
302 fetch: ctx._callSiteFetch ?? userCtx.fetch ?? ctx.fetch,
303 result:
304 userCtx.result !== undefined
305 ? userCtx.result
306 : userCtx instanceof Response
307 ? userCtx

Callers 2

userNextFunction · 0.85
executeMiddlewareFunction · 0.85

Calls 2

isRedirectFunction · 0.90
execValidatorFunction · 0.85

Tested by

no test coverage detected