To implement CSP (Content Security Policy) with a nonce using Modernizr.js, you’ll need to do the following steps:

  1. Generate a random nonce value on the server-side and add it to the CSP header.
  2. Modify your script tags to include the nonce attribute.
  3. Use Modernizr.js to detect features and conditionally load scripts.

Here’s an example of how you can achieve this:

  1. Generate the nonce on the server-side (e.g., using a backend language like Node.js) and set it in the CSP header. Make sure to replace 'YOUR_RANDOM_NONCE' with the actual nonce value.

For Node.js and Express:

const express = require('express');
const crypto = require('crypto');
const app = express();

app.use((req, res, next) => {
  // Generate a random nonce for each request
  const nonce = crypto.randomBytes(16).toString('base64');
  
  // Set the Content Security Policy header with the nonce
  res.setHeader('Content-Security-Policy', `script-src 'nonce-${nonce}'`);
  
  // Pass the nonce to the view
  res.locals.nonce = nonce;
  next();
});

// ... Your other routes and configurations ...

Modify your HTML template to use the nonce when loading scripts:

<!DOCTYPE html>
<html>
<head>
  <!-- Your other head elements... -->
</head>
<body>
  <!-- Your body content... -->

  <!-- Load Modernizr with the nonce -->
  <script nonce="{{nonce}}" src="path/to/modernizr.js"></script>

  <!-- Use Modernizr to conditionally load other scripts -->
  <script nonce="{{nonce}}">
    // Check for features and load scripts accordingly
    Modernizr.on('feature', () => {
      if (Modernizr.feature) {
        loadScript('path/to/your/feature/script.js');
      }
    });

    function loadScript(url) {
      const script = document.createElement('script');
      script.src = url;
      script.async = true;
      document.body.appendChild(script);
    }
  </script>
</body>
</html>

In this example, we set the CSP header to only allow scripts with the specified nonce, and then we use Modernizr to conditionally load other scripts based on feature detection. Make sure to replace 'path/to/modernizr.js' with the actual path to your Modernizr script and 'path/to/your/feature/script.js' with the paths to the scripts you want to load conditionally based on features.

By using the nonce attribute with Modernizr and other scripts, you’re enhancing the security of your website by allowing only trusted scripts to execute and mitigating the risk of XSS (Cross-Site Scripting) attacks.