Random UTF-8 characters


04 Jan 2020 in nextjsbugsnagherokusource mapsdevelopment

Setting up source maps (NextJS 9, BugSnag)

I recently set up bugsnag and had to fiddle around to get source maps working. I wanted to share my setup in case it is useful to anyone else out there. I'm using NextJS 9 and hosting my application on Heroku. This guide assumes you have already installed and configured bugsnag in your NextJS app.

Generating source maps

Zeit provides a nice plugin to generate source maps as part of your build: https://www.npmjs.com/package/@zeit/next-source-maps. To setup source maps install this package.

npm install --save-dev @zeit/next-source-maps

or if you are using yarn

yarn install --dev @zeit/next-source-maps

Then in your next.config.js import the plugin and configure it. I'm using a few other plugins here withOffline for PWA support, and withBundleAnalyzer to check the size of the resulting bundle. The key items are withSourceMaps and setting devtool: 'hidden-source-map'.

const withOffline = require('next-offline')
const withSourceMaps = require('@zeit/next-source-maps')

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true',

module.exports = withSourceMaps(withOffline(withBundleAnalyzer({
  devtool: 'hidden-source-map',
  publicRuntimeConfig: {
    BUG_SNAG_KEY: process.env.BUG_SNAG_KEY,
    STAGE: process.env.STAGE,
    VERSION: process.env.HEROKU_RELEASE_VERSION || 'dev',
    COMMIT: process.env.HEROKU_SLUG_COMMIT || 'dev',
  workboxOpts: {

Uploading source maps post build on Heroku

The first thing you should do is enable dyno metadata. This will give you access to the build and dyno metadata so we can properly link releases to their code.

heroku labs:enable runtime-dyno-metadata -a <app name>

Now if you pull your app's config you should see some additional metadata.

$ heroku config -a <your app>
=== <your app> Config Vars
BUG_SNAG_KEY:           hidden
HEROKU_APP_ID:             hidden
HEROKU_APP_NAME:           <your app>
HEROKU_SLUG_COMMIT:        <some_sha>
HEROKU_SLUG_DESCRIPTION:   Deploy <some_sha>

Next lets install bugsnag's upload CLI.

npm install --save-dev bugsnag-sourcemaps

or if you are using yarn

yarn install --dev bugsnag-sourcemaps

Sweet, now we have all the info we need to tell bugsnag about this release. We can set up a post build task that runs a script to upload our source maps. Lets add that to package.json:

  "scripts": {
    "postbuild": "./scripts/upload-sourcemaps.sh"

Then in the post build script /scripts/upload-sourcemaps.sh:

./node_modules/bugsnag-sourcemaps/cli.js --api-key $BUG_SNAG_KEY --app-version $HEROKU_RELEASE_VERSION --upload-sources --directory ./.next/ --overwrite

That's it, next time you release on heroku you should see source maps uploaded during the build process.