Replies: 1 comment
-
|
Request middleware in TanStack Start runs at the server/Nitro level before the router has matched a route, so the parameterized route path isn't directly available there. However, you can extract it from the request URL yourself. A couple of approaches: 1. Parse the URL manually in the middleware If you know your route patterns, you can match against them: // app/middleware.ts
import { createMiddleware } from "@tanstack/react-start"
export const tracingMiddleware = createMiddleware().server(async ({ next, request }) => {
const url = new URL(request.url)
const pathname = url.pathname
// Map to your parameterized patterns for tracing
const routePattern = matchRoutePattern(pathname)
// Use routePattern for your tracing span name
console.log(`[trace] ${routePattern} -> ${pathname}`)
return next()
})
function matchRoutePattern(pathname: string): string {
// Simple example — match /users/123 -> /users/:id
if (/^\/users\/[^/]+$/.test(pathname)) return "/users/:id"
if (/^\/posts\/[^/]+\/comments$/.test(pathname)) return "/posts/:id/comments"
return pathname
}2. Use route-level middleware instead If you need the actual matched route info, use // routes/__root.tsx
export const Route = createRootRoute({
beforeLoad: ({ location, context }) => {
// location.pathname is available
// Route.id gives you the route identifier
startTrace(Route.id, location.pathname)
},
})Or create a shared // routes/_layout.tsx
export const Route = createFileRoute("/_layout")({
beforeLoad: ({ location, matches }) => {
// matches gives you the matched route chain
const leafRoute = matches[matches.length - 1]
console.log(`Route: ${leafRoute.routeId}, Path: ${location.pathname}`)
},
})3. Server function middleware with context If your tracing is specifically for server functions, you can attach route info from the component side via headers or context that the server function reads. The short answer: request middleware is intentionally low-level and route-agnostic. For route-aware tracing, |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I want to get the parameterized route path in my request middleware so I can use it for tracing. Is this possible?
Beta Was this translation helpful? Give feedback.
All reactions