Blog>
Snippets

Creating Hashes for Inline Styles in Next.js 14

Detail how to use hashes to allow inline styles within a Content Security Policy in Next.js 14, exploring sha256, sha384, or sha512 hash generation.
import crypto from 'crypto';

export function generateInlineStyleHash(styleContent) {
  // Use the crypto module to create a hash of the CSS content
  const hash = crypto.createHash('sha256').update(styleContent).digest('base64');
  // Return the CSP compatible hash
  return `sha256-${hash}`;
}
This function takes a string containing CSS content and generates a base64-encoded SHA-256 hash. This hash can be used in a Content Security Policy to whitelist inline styles.