vite-plugin-bun-csp
v2.1.1
Published
A Vite plugin that generates and injects a Content Security Policy (CSP) for your SPA application.
Maintainers
Readme
Vite Plugin CSP Bun
Vite Plugin for adding a Content Security Policy to your Vite application using the Bun runtime.
Features
- ✨ Automatically calculates Subresource Integrity (SRI) hashes of JavaScript and CSS assets and adds them to the CSP.
- 📚 Automatically detects and handles Google Fonts.
- 🏎 Zero dependencies. Uses Bun's built-in implementation of Cloudflare's HTMLRewriter for parsing HTML.
Installation
bun add -D vite-plugin-bun-cspBasic Usage
Add the meta CSP tag to the <head> of your index.html file:
<head>
<meta http-equiv="Content-Security-Policy" content="" />
</head>Add the plugin to your Vite config
// vite.config.ts
import { defineConfig } from "vite";
import { generateCspPlugin } from "vite-plugin-bun-csp";
export default defineConfig({
root: "src",
build: {
outDir: "build",
},
plugins: [generateCspPlugin()],
});Configuration (Optional)
Note: Setting a config is optional. If no config is provided, then the default values will be used.
You can also manually configure the CSP. Even when manually setting the CSP, the plugin will still analyze the HTML, generate the integrity hashes and, automatically add them to the policy.
// vite.config.ts
import { defineConfig } from "vite";
import { generateCspPlugin } from "vite-plugin-bun-csp";
export default defineConfig({
root: "src",
build: {
outDir: "build",
},
plugins: [
generateCspPlugin({
algorithm: "sha256",
policy: {
"style-src": ["'self'", "'unsafe-inline'"],
"img-src": ["'self'", "data:"],
"upgrade-insecure-requests": [],
},
}),
],
});