Implementing CSP in Production
Implementing CSP in Production
Real-world CSP implementation requires careful planning and gradual deployment:
// Express.js CSP Implementation
const express = require('express');
const crypto = require('crypto');
app.use((req, res, next) => {
// Generate nonce for this request
const nonce = crypto.randomBytes(16).toString('base64');
res.locals.nonce = nonce;
// Build CSP header
const cspDirectives = [
`default-src 'self'`,
`script-src 'self' 'nonce-${nonce}' https://cdn.jsdelivr.net`,
`style-src 'self' 'nonce-${nonce}' https://fonts.googleapis.com`,
`img-src 'self' data: https:`,
`font-src 'self' https://fonts.gstatic.com`,
`connect-src 'self' https://api.example.com`,
`frame-ancestors 'none'`,
`base-uri 'self'`,
`form-action 'self'`,
`report-uri /csp-violation-report-endpoint`
];
res.setHeader('Content-Security-Policy', cspDirectives.join('; '));
next();
});