Top shelf web developer training.

Guided Paths

Follow our crafted routes to reach your goals.

Video Courses

Premium videos to build real apps.

Written Tutorials

Code to follow and learn from.

Find Your
Opportunity HIRED
Dismiss
Up

​Everything You Wanted to Know About JavaScript Source Maps

Related Course

Get Started with JavaScript for Web Development

JavaScript is the language on fire. Build an app for any platform you want including website, server, mobile, and desktop.

As developers, we naturally spend a lot of our time coding. Whilst the mental images we might conjure up of a web or mobile developer could entail playing sweet music with the voracious tapping of our keyboards late into the night building the next major software success story, the reality might be a little less glamorous.

Most developers spend just as much time on their technical debt, unit tests, meetings and dealing with technical support queries as they do actively building new features and functionality. Shipping days are usually a stop gap between all the extra ‘stuff’ a developer needs to achieve during a typical week.

(All developers code like this, right?)

Remember that technical customer support issue that cost you several days of lost productivity trying to hunt down the root cause? Yeah, it put you behind on all that other work you had to do right? Actually coding new code and building!

Developers want to build cool stuff and get it out into the world. Why’s that seem so hard to do sometimes?

One major gripe for software developers is dealing with bugs, crashes and customer support problems, mainly because it stops you moving forward and building new stuff as you have to stop and look backwards. You might catch many bugs in testing, but once your app is in the wild (in user’s hands), production bugs can crop up from the most unexpected places.

Modern day monitoring software can take away the pain of having to deal with these problems and if you don’t have monitoring in place already, you’re missing out.

By monitoring, I don’t mean looking at the performance of your servers and if there are any queries timing out, or a worker is having a hard time, I’m talking about real problems and issues your users are running into whilst using your applications right now. Things that are affecting them directly, because they sure ain't submitting support tickets for them.

Introducing Raygun as the ultimate error monitoring tool

Real time error monitoring solutions like Raygun can ping your team’s Slack channel when they experience a bug stopping them make a purchase on your website, notify you of 500 errors when they try to navigate to different screens, or show you all of the errors you introduced (or fixed) each time you made a deployment.

If you’re not using something like Raygun already, you’re simply flying blind, and I can guarantee you that your users are suffering the effects.

Raygun

A tool like Raygun can raise awareness of issues that are present in your codebase and offer full diagnostic information on how to fix the issue, but JavaScript errors are complex, there are a number of things that can muddy the waters.

Third party scripts, older browsers and minified code can all lead you down a path to much noise, little signal when tracking down the root causes of problems in your codebase.

When exceptions occur in minified/combined JavaScript assets, the stack trace information is based on the line and column position of the code in the minified file.

Unfortunately this does not match up with the original source code and finding the true origin of the error can take an incredibly long time, especially in code bases with large amounts of JavaScript assets being compiled together.

Here we’ll be taking a deep dive into how minified JavaScript can produce readable stack traces by just making a few small changes to our workflow.

What are JavaScript Source maps and how do they work?

Source maps are a useful tool for debugging and fixing minified JavaScript code without the hassle of determining where in the original code an error occurred. They provide a way to translate between minified code, designed to decrease webpage load times, to the source code the developer writes.

Source maps provide you with the ability to decode how the files were combined and minified so that the exception stack trace information can be properly mapped back to the original source code. This gives you the same ease of debugging, while still allowing you to use these faster loading JavaScript assets.

Stack Trace Diagram

If you're unfamiliar with source maps, it's probably best to see how they work within the browser.

Source maps are natively supported by both Google Chrome and Firefox, as well as IE11. This means that any minified JavaScript files with a source map comment at the bottom will automatically link to it’s sources, so long as the mapping and source files are in the correct locations.

This allows errors to be mapped onto the original source code instead of reporting errors on only the minified script.

For instance if a minified file example.min.js has the following comment at the end of the file

//# sourceMappingURL=example.js.map

the browser will load the mapping file example.js.map in the same directory as the minified file. Any source files specified by the mapping file will then be loaded into the Sources window in the browser console.

In addition to showing the source files in the sources window, any errors which happen within the minified file will automatically be mapped into the source files allowing for easy debugging.

Getting started with Raygun

Whether you are currently monitoring your web or mobile application with any sort of tool you’re still going to get a huge amount of benefit from giving Raygun a try. Just a few minutes is all that it takes to copy and paste the Raygun code snippet into your app (Raygun has instructions for every major programming language and platform) and deploy to production. Raygun will instantly start finding issues that are affecting your users once included in your code. In the image below, you can see an error has been thrown by your application:

Error Thrown

Try Raygun free here.

In this guide, we’ll be using Raygun’s error monitoring software to monitor a JavaScript application, which means we could also try out Raygun’s Real User Monitoring product Raygun Pulse to identify UX performance issues, but for now let's stick with getting our JavaScript source maps set up.

What you’re going to need

Raygun requires the following to complete the decode process of a JavaScript source map:

  • A working Raygun account

  • Valid line/column numbers to be present in at least one line of the stack trace

  • An accessible minified JavaScript file as specified in the stack trace. This is either downloaded or retrieved from the source map center to determine if there is map file present

  • The map file to be correctly indicated in the minified JavaScript file using a footer comment

  • An accessible source map file (either publicly hosted or uploaded to the source map center)

To provide inline code snippets we also require the sources content field of the map file to be present or for the map file to point to publicly accessible unminified source JavaScript files. If neither of these are provided decoding of line numbers and variable names can still succeed but no inline code will be displayed with the stack trace

Validating your Source maps for use

Ensure that your source maps are compatible with Raygun by using this handy validation tool that allows you to validate your source map files for use with Raygun

Drag and Drop

Uploading private JavaScript files to Raygun

If you do not wish to have publicly accessible JavaScript files you can upload them directly to Raygun from the JS Source Map Center. This is within the Application Settings submenu on the main dashboard.

Validate Drag and Drop

Within the Source Map Center you can upload files and label them with the URL they would normally be accessed from. When a JavaScript error is mapped, Raygun uses the files you uploaded instead of trying to access them from your servers.

In addition to the upload page Raygun offers an API endpoint. The URL is displayed in the Source Map Center and is specific to each application.

Simply send a post request with "URL" and "file" parameters specified to upload the file.

Here is a cURL example request using Basic Authorization:

-X POST
-u email@example.com:password
-F "url=http://example.com/myjs.min.js"
-F "file=@C:\website\js\myjs.min.js"

https://app.raygun.io/upload/jssymbols/MyAppId

Here is an example using the Grunt plugin grunt_http_upload using an External Access Token:

http_upload: {
    your_target: {
        options: {
            url: 'https://app.raygun.io/upload/jssymbols/MyAppId?authToken=MyExternalAuthToken',
            method: 'POST',
            data: {
                url: 'http://example.com/myjs.min.js'
            }
        },
        src: 'C:\website\js\myjs.min.js',
        dest: 'file'
    }       
}

Recommended minifier tooling

I recommend using UglifyJS2 to generate a source map file. Both the minified JS and its map file should use relative pathing. Look into the -p and --source-map-root options.

To install it you will need Node.js installed, you can then run:

npm install uglify-js -g

This will install Uglify so that it's globally available which is what you will typically want.

To produce minified JavaScript we can simply run

uglifyjs example.js -o example.min.js

To produce minified JavaScript with a mapping file we can run

uglifyjs example.js -o example.min.js --source-map example.min.js.map

This produces the minified file "example.min.js" as well as a source map file "example.min.js.map"

If you deploy the minified file example.min.js to production but do not wish for any or some of these files to be publicly accessible, you will need to upload these files to Raygun to get source mapped stacktraces in the JS Source Map Center.

Putting it all together

Looks like one of our users has ran into an error and we can now click through to view the diagnostic information in Raygun.

Example Error

Raygun has already produced the stack trace as well from our minified JavaScript files, here’s what the stack trace looks like. Voila!

Stack Trace In Raygun

Conclusion

I hope this article was useful to answer many of the questions around why you should consider using monitoring alongside utilizing the benefits JavaScript source maps can offer. Minified JavaScript might improve your page load speeds, but could also slow you down considerably when trying to debug issues in your codebase.

Now you’ll get the best of both worlds, with speedy page load speeds and full diagnostic information and stack traces whenever users run into bugs in your software applications. You can find out more about Raygun and start a free trial here.

This content is sponsored via Syndicate Ads.

This content is sponsored via Syndicate Ads

Nick Harley

Nick is a Senior Product Marketer at Raygun and helps developer teams to get started with Raygun products. Having worked in the web development industry for several years, seeing the benefits that Raygun brings to software development teams has been extremely rewarding. He loves to see customers getting success out of Raygun products.