DEV Community

webdiscus
webdiscus

Posted on

Auto generate an integrity hash for `link` and `script` tags in an HTML template

What is integrity hash?

The subresource integrity hash is a cryptographic value of the integrity attribute that used by a browser to verify that the content of an asset has not been manipulated. If the asset has been manipulated, the browser will never load it.

The integrity attribute can be used with the script and link tags.

Webpack plugins

You need to install two Webpack plugins: one generates hashes, the other injects them into HTML tags.

The webpack-subresource-integrity plugin generates a hash value for all source scripts and styles and stores them in an internal property of the compiled assets.

The html-bundler-webpack-plugin extracts the hashes from internal property of compiled assets and adds them to link and script tags when generating HTML.

For example, we have a simple HTML template with a script and a style:

<html>
  <head>
    <!-- include source style -->
    <link href="./style.scss" rel="stylesheet" />
    <!-- include source script -->
    <script src="./main.js" defer="defer"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Add the plugins in your Webpack config:

const { SubresourceIntegrityPlugin } = require('webpack-subresource-integrity');
const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');

module.exports = {
  output: {
    // required for subresource integrity to work
    crossOriginLoading: 'anonymous',
  },
  plugins: [
    // renders templates and injects integrity hash
    new HtmlBundlerPlugin({
      entry: {
        index: 'src/views/index.html', // template where are included link and script tags
      },
      integrity: 'auto', // include `integrity` hash in production mode only
    }),
    // generates integrity hash
    new SubresourceIntegrityPlugin(),
  ],
};
Enter fullscreen mode Exit fullscreen mode

The generated HTML file dist/index.html contains the integrity hashes:

<html>
  <head>
    <link
      href="assets/css/style.css"
      rel="stylesheet"
      integrity="sha384-gaDmgJjLpipN1Jmuc98geFnDjVqWn1fixlG0Ab90qFyUIJ4ARXlKBsMGumxTSu7E"
      crossorigin="anonymous" />

    <script
      src="assets/js/main.js"
      defer="defer"
      integrity="sha384-E4IoJ3Xutt/6tUVDjvtPwDTTlCfU5oG199UoqWShFCNx6mb4tdpcPLu7sLzNc8Pe"
      crossorigin="anonymous"></script>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Note

The integrity hash is generated when using webpack build in the production mode.
When using webpack watch or serve, no hashes will be generated because it doesn't make sense.

View in browser

Open in StackBlitz

Open generated dist/index.html. The link and script tags will contain the integrity attribute with a hash.

Top comments (0)