---
title: Adding sub-resource integrity with Importmap & Rails
url: https://calvin.my/posts/adding-sub-resource-integrity-with-importmap-rails
published: 2025-11-15
updated: 2026-09-16
category: Development
tags:
- Security
- SRI
- Rails
- Importmap
summary: The post explains how to enable Subresource Integrity for Rails assets, especially files generated during builds whose hashes must be recalculated. Rails can generate integrity hashes by selecting an algorithm, enabling integrity on stylesheet tags, and activating Importmap support in its configuration. The result is generated stylesheet and module preload tags containing integrity attributes, allowing browsers to verify that loaded assets have not been altered.
---

# Adding sub-resource integrity with Importmap & Rails

## The Problem

To enable the&nbsp;[sub-resource integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) feature, a cryptographic hash string of the resource file is required. For static files or resources hosted by a CDN, this hash string would also be static and is often provided. However, for resources generated at build time, we will need to calculate the hash string for each build.

Fortunately, Rails supports this natively. We can enable the feature.

* * *

## The Solution

1. Configure the hash algorithm. (E.g., sha 384)

   ```ruby
   config.assets.integrity_hash_algorithm = "sha384"
   ```

2. Enable integrity hash for stylesheets.

   ```erb
   <%= stylesheet_link_tag :app, "data-turbo-track": "reload", integrity: true %>
   ```

3. If importmap is used, we need to configure \`importmap.rb\`

   ```javascript
   enable_integrity! # Add this
   
   pin "application"
   pin "@hotwired/turbo-rails", to: "turbo.min.js"
   pin "@hotwired/stimulus", to: "stimulus.min.js"
   pin "@hotwired/stimulus-loading", to: "stimulus-loading.js"
   pin_all_from "app/javascript/controllers", under: "controllers"
   ```

* * *

## The Result

You will now see the sha384 integrity hash generated.

```html
<link rel="stylesheet" href="/assets/application-2b...51.css" data-turbo-track="reload" integrity="sha384-+tCm0...rFL+LZ" />
<link rel="modulepreload" href="/assets/application-bf...40.js" nonce="0M...0vg==" integrity="sha384-HzsVkF25...RiKvPXZO">
```
