Mo

BlogStartup ideasTwitter

Typescript sourcemaps with Sentry

CODE BITES

Sentry can be difficult at times to get right. I spent a few hours trying to get a proper sourcemapping working with Typescript and our API server. Here is our setup:

src/index.ts
Sentry.init({
  dsn: SENTRY_DSN,

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,

  release: process.env.HEROKU_SLUG_COMMIT,

  integrations: [
    new RewriteFrames({
      root: process.cwd(),
    }),
    new Sentry.Integrations.Http({ tracing: true }),
    new Tracing.Integrations.Postgres(), // Add this integration
  ],
});

Notice root: process.cwd(). We are setting the root for rewrite frames to the root of the repo. On heroku, this is /app.

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2017",
    "module": "commonjs",
    "lib": ["es6", "es2017", "esnext.asynciterable"],
    "skipLibCheck": true,
    "outDir": "./build",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "allowJs": true
  },
  "exclude": ["node_modules"],
  "include": ["./src/**/*.tsx", "./src/**/*.ts", "src/modules.d.ts"]
}

Notice our outDir is set to build.

tsconfig.prod.json
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "sourceMap": true,
    "removeComments": true,
    "inlineSources": true,
    "sourceRoot": "/",
    "noEmitHelpers": true,
    "importHelpers": true
  },
}

sourceMap is set to "/"

Finally, building and releasing on Sentry:

package.json
{
  "scripts": {
    "prebuild": "del ./build",
    "build": "tsc --project tsconfig.prod.json",
    "sentry-release": "sentry-cli releases files \"$HEROKU_SLUG_COMMIT\" upload-sourcemaps --url-prefix '~/app/build' ./build"
  }
}

This is where the magic happens. This is where we tell Sentry to prefix all the assets with ~/app/build. This allows everything to magically connect and you have sourcemaps!


If you enjoyed this post, feel free to follow me on Twitter or email where you can stay up to date on upcoming content and life updates