Disable JavaScript source maps in production Rails applications
By Martijn Storck
Ruby on Rails 6 allows us to leverage the excellent Webpack bundler to manage JavaScript and CSS components in a way that’s more native to those technologies than the old asset pipeline: no more gems to wrap JavaScript libraries and no more libv8 gem issues.
Another advantage Webpack brings is the excellent source maps. I was surprised to see the source code of my Svelte components, complete with comments available from the Firefox development tools:
If you’re old enough to have developed CoffeeScript on early 2010’s browser technology you will understand my surprise.
One design decision that the Rails Webpacker team made is to enable these source maps on production be default. I found some discussion on GitHub issues debating this policy but the developers seemed to have stuck with it. This means your source code is available for all to see, copy and prod. That includes your TODO and FIXME or other embarrassing comments (like the one in the image above) and the Svelte components you worked so hard on.
My recommendation is to disable the generation of source maps for production deploys by modifying your config/webpack/production.js
as follows:
process.env.NODE_ENV = process.env.NODE_ENV || 'production'
const environment = require('./environment')
const config = environment.toWebpackConfig()
config.devtool = 'none'
module.exports = config
By setting config.devtool
to none
you prevent the generation of devmaps and only serve the minified (and thus slightly obfuscated) JavaScript to your users.
But now the line numbers in my error reports are gone!
If you do error reporting on the client-side with a tool like Sentry, the source maps are actually
useful because they allow your error reports to contain line numbers of your actual code files instead of the
obfuscated ones. Luckily the nosources-source-map
settings providers a middle ground that creates
a source map without the full source content.
config.devtool = 'nosources-source-map'
There are more options for the source map generation in production and it’s worth seeing which one works for you. See the webpack documentation on the devtool option for all the available options.