Deploying Content-Security-Policy
Guide on how to deploy content-security-policy
Content-Security-Policy is delivered over an HTTP response header. For a Strict CSP, dynamic servers generate a fresh, cryptographically random nonce on every request, include it in the Content-Security-Policy-Report-Only (or Content-Security-Policy) header, and pass that same nonce to HTML <script nonce="..."> tags.
The examples below show how to deploy a Strict CSP with both report-uri and report-to (Reporting-Endpoints) across common frameworks and web servers.
Examples
NodeJS / Express
const crypto = require("crypto");
const reportEndpoint = "https://YOUR_PROJECT.endpoint.csper.io/?v=1";
app.use((req, res, next) => {
const nonce = crypto.randomBytes(16).toString("hex");
res.locals.cspNonce = nonce;
res.setHeader("Reporting-Endpoints", `csp-endpoint="${reportEndpoint}"`);
res.setHeader(
"Content-Security-Policy-Report-Only",
`script-src 'nonce-${nonce}' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; report-uri ${reportEndpoint}; report-to csp-endpoint`
);
next();
});Then pass res.locals.cspNonce into your HTML templates (<script nonce="<%= cspNonce %>" src="/app.js"></script>).
Go
type contextKey string
const cspNonceKey contextKey = "cspNonce"
func generateCSPNonce() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func SecurityHeaders(next http.Handler) http.Handler {
reportEndpoint := "https://YOUR_PROJECT.endpoint.csper.io/?v=1"
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
nonce, err := generateCSPNonce()
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
csp := fmt.Sprintf(
"script-src 'nonce-%s' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; report-uri %s; report-to csp-endpoint",
nonce, reportEndpoint,
)
w.Header().Set("Reporting-Endpoints", fmt.Sprintf(`csp-endpoint="%s"`, reportEndpoint))
w.Header().Set("Content-Security-Policy-Report-Only", csp)
ctx := context.WithValue(r.Context(), cspNonceKey, nonce)
next.ServeHTTP(w, r.WithContext(ctx))
})
}Read the nonce from r.Context().Value(cspNonceKey) when rendering your HTML templates or SPA index.html.
Django
import secrets
REPORT_ENDPOINT = "https://YOUR_PROJECT.endpoint.csper.io/?v=1"
class CSPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
nonce = secrets.token_hex(16)
request.csp_nonce = nonce
response = self.get_response(request)
response["Reporting-Endpoints"] = f'csp-endpoint="{REPORT_ENDPOINT}"'
response["Content-Security-Policy-Report-Only"] = (
f"script-src 'nonce-{nonce}' 'strict-dynamic' 'report-sample'; "
f"object-src 'none'; base-uri 'none'; "
f"report-uri {REPORT_ENDPOINT}; report-to csp-endpoint"
)
return response
# In settings.py
MIDDLEWARE = [
...,
"appname.middleware.CSPMiddleware",
...
]Then use {{ request.csp_nonce }} on <script nonce="{{ request.csp_nonce }}"> tags in your Django templates.
Apache (Static / Hash-Based Strict CSP)
For static files served directly by Apache without per-request HTML templating, use a hash-based Strict CSP ('sha256-...') instead of a nonce:
.htaccess
# Under VirtualHost
Header set Reporting-Endpoints "csp-endpoint=\"https://YOUR_PROJECT.endpoint.csper.io/?v=1\""
Header set Content-Security-Policy-Report-Only "script-src 'sha256-YOUR_SCRIPT_HASH' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; report-uri https://YOUR_PROJECT.endpoint.csper.io/?v=1; report-to csp-endpoint"Nginx (Static / Hash-Based Strict CSP)
Similarly, when setting static headers in Nginx, use a hash-based Strict CSP:
nginx.conf
# in server {} block
add_header Reporting-Endpoints 'csp-endpoint="https://YOUR_PROJECT.endpoint.csper.io/?v=1"' always;
add_header Content-Security-Policy-Report-Only "script-src 'sha256-YOUR_SCRIPT_HASH' 'strict-dynamic' 'report-sample'; object-src 'none'; base-uri 'none'; report-uri https://YOUR_PROJECT.endpoint.csper.io/?v=1; report-to csp-endpoint" always;Report-Only
The first time CSP is rolled out, it is highly recommended to use it in Content-Security-Policy-Report-Only mode.
In report-only mode, the browser won't block any scripts—it will only send violation reports to your endpoint. Once your reports are clean, switch the header name to Content-Security-Policy to enforce the policy.