Production CSP Implementation
Production CSP Implementation
Production React applications require stricter CSP policies that eliminate unsafe practices while maintaining functionality. Implementing nonce-based CSP provides the best security:
// server.js - Express server with CSP for React
const express = require('express');
const crypto = require('crypto');
const path = require('path');
const app = express();
// Generate nonce for each request
app.use((req, res, next) => {
res.locals.nonce = crypto.randomBytes(16).toString('base64');
next();
});
// Serve static files with CSP headers
app.use(express.static(path.join(__dirname, 'build'), {
setHeaders: (res, path) => {
const nonce = res.locals.nonce;
res.setHeader(
'Content-Security-Policy',
`default-src 'self'; ` +
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https: 'unsafe-inline'; ` +
`style-src 'self' 'nonce-${nonce}'; ` +
`img-src 'self' data: https:; ` +
`font-src 'self'; ` +
`connect-src 'self' https://api.yourdomain.com; ` +
`base-uri 'self'; ` +
`form-action 'self'; ` +
`frame-ancestors 'none'; ` +
`object-src 'none';`
);
}
});
// Modify HTML to include nonce
app.get('*', (req, res) => {
const nonce = res.locals.nonce;
const indexPath = path.join(__dirname, 'build', 'index.html');
fs.readFile(indexPath, 'utf8', (err, data) => {
if (err) {
return res.status(500).send('Error loading index.html');
}
// Add nonce to script tags
const modifiedHtml = data.replace(
/<script/g,
`<script nonce="${nonce}"`
);
res.send(modifiedHtml);
});
});