How to get current route in loader? #9740
-
I would like to attach a span attribute of url.route in our OTEL instrumentation. While I statically know in a louder which route it is, it would be a pain to write out a constant every time. Is the value available some how like it is for useMatches on the client? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
Are you referring to the route ID? Remix doesn't provide an easy way to access the route configuration directly. However, if you're using one of the custom adapters, like Express, you can include the routes config from the server build using const build = viteDevServer
? () => viteDevServer.ssrLoadModule("virtual:remix/server-build")
: await import("./build/server/index.js");
const remixHandler = createRequestHandler({
build,
getLoadContext: async () => {
const serverBuild = await build();
return { routes: serverBuild.routes };
},
});
{
root: {
id: 'root',
parentId: undefined,
path: '',
index: undefined,
caseSensitive: undefined,
module: {
Layout: [Getter],
default: [Function: App],
[Symbol(Symbol.toStringTag)]: 'Module'
}
},
'routes/user.$id': {
id: 'routes/user.$id',
parentId: 'routes/user',
path: ':id',
index: undefined,
caseSensitive: undefined,
module: {
loader: [Getter],
action: [Getter],
default: [Function: Component],
[Symbol(Symbol.toStringTag)]: 'Module'
}
},
// ... snip ...
} Now, you can use that config to find the route that matches the current running loader. function getRouteIdForLoader(routes: ServerBuild["routes"], loader: LoaderFunction) {
return Object.values(routes).find(route => route.module?.loader === loader)?.id
}
export async function loader({ context }: LoaderFunctionArgs) {
const routeId = getRouteIdForLoader(context.routes, loader)
// ...
} See #9265 (comment) |
Beta Was this translation helpful? Give feedback.
Are you referring to the route ID?
Remix doesn't provide an easy way to access the route configuration directly.
However, if you're using one of the custom adapters, like Express, you can include the routes config from the server build using
getLoadContext
.ServerBuild.routes
returns a route object that looks something like this: