Skip to content

Tracing integration with express erases router metadata #5050

@jondot

Description

@jondot

Is there an existing issue for this?

How do you use Sentry?

Sentry Saas (sentry.io)

Which package are you using?

@sentry/node

SDK Version

6.19.7

Framework Version

6.19.7

Link to Sentry event

No response

Steps to Reproduce

Integrate sentry with an existing express app.
Use this to list routes:

import path from 'path'

function getPathFromRegex(regexp) {
  return regexp
    .toString()
    .replace('/^', '')
    .replace('?(?=\\/|$)/i', '')
    .replace(/\\\//g, '/')
}

function combineStacks(acc, stack) {
  if (stack.handle.stack) {
    const routerPath = getPathFromRegex(stack.regexp)
    return [
      ...acc,
      ...stack.handle.stack.map((stack) => ({ routerPath, ...stack })),
    ]
  }
  return [...acc, stack]
}

function getStacks(app) {
  // Express 3
  if (app.routes) {
    // convert to express 4
    return Object.keys(app.routes)
      .reduce((acc, method) => [...acc, ...app.routes[method]], [])
      .map((route) => ({ route: { stack: [route] } }))
  }

  // Express 4
  if (app._router && app._router.stack) {
    return app._router.stack.reduce(combineStacks, [])
  }

  // Express 4 Router
  if (app.stack) {
    return app.stack.reduce(combineStacks, [])
  }

  // Express 5
  if (app.router && app.router.stack) {
    return app.router.stack.reduce(combineStacks, [])
  }

  return []
}

function listRoutes(app) {
  const stacks = getStacks(app)
  const routes = []

  if (stacks) {
    for (const stack of stacks) {
      if (stack.route) {
        const routeLogged = {}
        for (const route of stack.route.stack) {
          const method = route.method ? route.method.toUpperCase() : null
          if (!routeLogged[method] && method) {
            const stackPath =
              stack.routerPath || route.path
                ? path.resolve(
                    [stack.routerPath, stack.route.path, route.path]
                      .filter((s) => !!s)
                      .join('')
                  )
                : stack.route.path
            routes.push({ verb: method, path: stackPath })
            routeLogged[method] = true
          }
        }
      }
    }
  }
  return routes
}

export default listRoutes

Expected Result

routes listed and returned

Actual Result

after integration with Sentry, all route information disappears.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions