vite-plugin-csp

raw JSON →
1.1.2 verified Mon Apr 27 auth: no javascript maintenance

A Vite plugin that generates Content Security Policy meta tags and HTTP headers (CSP, CSP Report-Only, Report-To, Referrer-Policy) from all sources in the final HTML. Current stable version is 1.1.2 (June 2022). Uses csp-typed-directives for typed CSP directives. Compatible with csp-html-webpack-plugin configuration. No official releases since 2022; project appears in maintenance mode. Key differentiators: automated policy generation from Vite build output, TypeScript support, and header validation.

error Module "vite-plugin-csp" has no exported member 'ViteCspPlugin'.
cause Named import used for default export.
fix
Use import ViteCspPlugin from 'vite-plugin-csp' (no braces).
error Cannot find module 'vite-plugin-csp' or its corresponding type declarations.
cause TypeScript may not resolve types if skipLibCheck is false and types are missing.
fix
Add "types": ["vite-plugin-csp"] in tsconfig or ensure moduleResolution is 'node'.
error Error: The csp plugin only supports scripts and styles.
cause Used directive like 'img-src' which is not supported.
fix
Remove unsupported directives from policy; only 'script-src', 'style-src', and 'report-to' work.
error Error: Nonce generation is not supported in server-side rendering.
cause Used nonceEnabled: true with SSR.
fix
Set nonceEnabled: false or avoid SSR.
gotcha Relative module paths are resolved relative to CWD, not the file location.
fix Use absolute paths or resolve manually with path.resolve(__dirname, ...).
gotcha No SSR support (and thus no nonce support).
fix Do not use in SSR environments; avoids nonce-based CSP.
gotcha Only script and style related directives are supported (except report-to).
fix Add other directives manually if needed; plugin ignores them.
gotcha No parsing of JS embedded sources (requires framework-specific plugins).
fix Manually include inline script hashes in policy.
deprecated Project has not been updated since June 2022; consider alternatives for active development.
fix Evaluate vite-plugin-csp2 or other actively maintained CSP plugins.
npm install vite-plugin-csp
yarn add vite-plugin-csp
pnpm add vite-plugin-csp

Demonstrates minimal Vite CSP plugin configuration with custom policies.

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

export default defineConfig({
  plugins: [
    ViteCspPlugin({
      policies: {
        'script-src': ["'self'", 'https://apis.google.com'],
        'style-src': ["'self'", "'unsafe-inline'"],
      },
      hashEnabled: true,
      nonceEnabled: false,
    }),
  ],
});