Uploading Honeybadger source maps with esbuild and Sprockets

Curated ago by @jeremysmithco

Description

If you are using Honeybadger for JS error monitoring on your Rails app, you may want to upload source maps so they can be applied to JS stack traces.

Here’s how you can do that if you are using esbuild, Sprockets, and deploying to Heroku. The source map will be uploaded to Honeybadger during the build phase, via a Rake task enhancing the assets:precompile step.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
namespace :assets do
  desc "Upload source map"
  task upload_sourcemap: :environment do
    if !Rails.env.production?
      puts "Not uploading source map, not a deployed environment"
      exit 0
    end

    manifest_file = Rails.public_path.glob("assets/.sprockets-manifest-*.json").first
    parsed_manifest = JSON.parse(manifest_file.read, symbolize_names: false)
    sourcemap_asset = parsed_manifest.dig("assets", "application.js.map")
    javascript_asset = parsed_manifest.dig("assets", "application.js")

    endpoint = "https://api.honeybadger.io/v1/source_maps"
    revision = ENV["SOURCE_VERSION"]
    sourcemap_file = Rails.public_path.join("assets", sourcemap_asset)
    javascript_file = Rails.public_path.join("assets", javascript_asset)
    javascript_url = "https://*/assets/#{javascript_file.basename}"

    puts "Uploading source map..."
    puts "- revision: #{revision}"
    puts "- minified_url: #{javascript_url}"
    puts "- sourcemap: #{sourcemap_file.basename}"

    HTTP.post(
      endpoint,
      form: {
        api_key: ENV["HONEYBADGER_API_KEY_JS"],
        revision: revision,
        minified_url: javascript_url,
        source_map: HTTP::FormData::File.new(sourcemap_file),
        minified_file: HTTP::FormData::File.new(javascript_file)
      }
    )

    puts "Finished uploading source map"
  end
end

if Rake::Task.task_defined?("assets:precompile")
  Rake::Task["assets:precompile"].enhance do
    Rake::Task["assets:upload_sourcemap"].execute
  end
end

This Rake task enhances assets:precompile. During the Heroku build step, SOURCE_VERSION var is the commit hash for this build.