Last active
December 5, 2023 13:39
-
-
Save brunojppb/2ab8fc62ca99518fb4c299d2f446505b to your computer and use it in GitHub Desktop.
How to match Remix routes with route patterns so we can track using tracing libraries like Datadog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { matchPath } from '@remix-run/react' | |
import fs from 'node:fs' | |
import * as path from 'node:path' | |
/** | |
* Given a request path, tries to find a Remix route path pattern | |
* that matches with an existing route in your Remix app. | |
* | |
* Make sure to generate the Remix routes file during your build with: | |
* | |
* ```shell | |
* npx @remix-run/dev routes --json >> build/remix_routes.json | |
* ``` | |
*/ | |
export function matchRemixRoutePattern(requestPath: string) { | |
const routes = loadRoutesFile() | |
for (const routePattern of routes) { | |
if (matchPath(routePattern, requestPath) !== null) { | |
return routePattern | |
} | |
} | |
return null | |
} | |
let routesCache: string[] | null = null | |
function loadRoutesFile() { | |
if (routesCache) { | |
return routesCache | |
} | |
const buildFolder = path.resolve(process.cwd(), 'build') | |
const routesData = fs.readFileSync( | |
path.resolve(buildFolder, 'remix_routes.json'), | |
{ encoding: 'utf8', flag: 'r' } | |
) | |
const routesJson = JSON.parse(routesData) | |
routesCache = flattenRoutes(routesJson) | |
return routesCache! | |
} | |
function flattenRoutes(json: any[]) { | |
let paths: string[] = [] | |
for (const entry of json) { | |
if (entry.children) { | |
const mappedPaths = flattenRoutes(entry.children) | |
.filter(path => typeof path !== 'undefined') | |
.map(path => `${entry.path}/${path}`) | |
paths = [...paths, entry.path, ...mappedPaths] | |
} else { | |
paths.push(entry.path) | |
} | |
} | |
return paths | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tracer from 'dd-trace' | |
import { matchRemixRoutePattern } from './routeMatcher' | |
tracer.init() | |
tracer.use('express', { | |
hooks: { | |
request: (span, req, res) => { | |
if (req?.url) { | |
try { | |
const url = new URL(req.url) | |
const matchPattern = matchRemixRoutePattern(url.pathname) | |
if (matchPattern) { | |
span?.setTag('http.route', matchPattern) | |
} | |
} catch (error: unknown) { | |
console.error('Invalid referer', error) | |
} | |
} | |
}, | |
}, | |
}) | |
export default tracer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment