title: Rails 5.2: Best practice for setting CSP nonce
body: <p>Our application is on Rails 5.2 and it is serving assets with webpacker without the asset pipeline. I was wondering what is the best way to set the nonce attributes on the script tag. </p>
  
  <p>In <code>content_security_policy.rb</code>, there is a <code>content_security_policy_nonce_generator</code> for UJS, I was wondering if I can still use that without any side effect. The following work and I was just wondering what is the best practice for doing something like this. </p>
  
  <pre><code>#initializers/content_security_policy.rb
  
  # If you are using UJS then enable automatic nonce generation
  Rails.application.config.content_security_policy_nonce_generator = -&gt; request { SecureRandom.base64(16) 
  </code></pre>
  
  <p>In <code>application.html.erb</code>, if I want to have nonce on the script tag, I will have to get it from the request. According here: <a href="https://api.rubyonrails.org/classes/ActionDispatch/ContentSecurityPolicy/Request.html#method-i-content_security_policy_nonce" rel="noreferrer">https://api.rubyonrails.org/classes/ActionDispatch/ContentSecurityPolicy/Request.html#method-i-content_security_policy_nonce</a></p>
  
  <pre><code>#app/views/layouts/application.html.erb
  
  &lt;!DOCTYPE html&gt;
  &lt;html dir="ltr"&gt;
    &lt;head&gt;
      &lt;title&gt;FruitsMarket&lt;/title&gt;
      &lt;%= csrf_meta_tags %&gt;
      &lt;%= csp_meta_tag %&gt;
  
      &lt;%= stylesheet_pack_tag 'application' %&gt;
      &lt;%= javascript_pack_tag 'polyfills' %&gt;
      &lt;%= javascript_pack_tag 'application' %&gt;
      &lt;script type="text/javascript" nonce=&lt;%= request.content_security_policy_nonce %&gt;&gt;
        alert('hi');
      &lt;/script&gt;
    &lt;/head&gt;
  
    &lt;body&gt;
      &lt;%= yield %&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>