vite-plugin-csp-guard

raw JSON →
4.0.1 verified Mon Apr 27 auth: no javascript

Vite plugin for generating Content Security Policy (CSP) headers in single-page applications. Current stable version 4.0.1, requires Vite ^8.0.0. Supports automatic hashing of inline scripts/styles, SRI integrity, nonces for SSR, and policy validation. Key differentiators include first-class SPA support, dev-mode CSP enforcement, and framework integration for Vue Router and React. Previously released under csp-toolkit; actively maintained with frequent releases.

error Cannot find module 'vite-plugin-csp-guard' or its corresponding type declarations.
cause Package not installed or ESM-only module imported via CommonJS require.
fix
Use ES module import syntax: import csp from 'vite-plugin-csp-guard'
error The requested module 'vite-plugin-csp-guard' does not provide an export named 'csp'
cause Attempting named import instead of default import.
fix
Use import csp from 'vite-plugin-csp-guard' without curly braces.
error Uncaught (in promise) SecurityError: Failed to execute 'postMessage' on 'Window': Content Security Policy violation
cause Policy too strict or missing allowed sources.
fix
Add appropriate sources to your policy (e.g., 'self', specific domains).
breaking Version 4.0.0 requires Vite ^8.0.0; older Vite versions are incompatible.
fix Upgrade Vite to 8.x or use version 3.x of this plugin.
breaking Version 3.0.0 dropped support for Vite 6 and earlier.
fix Ensure Vite 7 is installed, or downgrade to version 2.x.
gotcha Dev mode CSP enforcement requires `dev: { run: true }` in configuration; defaults to false.
fix Set `dev: { run: true }` in the plugin options.
deprecated The package was previously named `csp-toolkit`; older versions may have different API.
fix Migrate to new import: `import csp from 'vite-plugin-csp-guard'`.
gotcha Policy must be an object; string policies are not supported.
fix Always pass an object like `{ 'script-src': ["'self'"] }`.
gotcha Nonces require SSR set-up; not available in pure client-side builds.
fix Configure SSR in Vite and use `nonce` option.
npm install vite-plugin-csp-guard
yarn add vite-plugin-csp-guard
pnpm add vite-plugin-csp-guard

Basic setup for vite-plugin-csp-guard with a CSP policy allowing self and specific external sources.

// vite.config.ts
import { defineConfig } from 'vite';
import csp from 'vite-plugin-csp-guard';

export default defineConfig({
  plugins: [
    csp({
      algorithm: 'sha256',
      dev: { run: true },
      policy: {
        'script-src': ["'self'", 'https://www.google-analytics.com'],
        'style-src': ["'self'", 'https://fonts.googleapis.com'],
      },
    }),
  ],
});