Setting CSP Headers on the Server
You'll learn: How to configure Content Security Policy headers in Node.js, Apache, and Nginx server environments.
Now that you understand CSP syntax, it's time to actually send these headers from your server. Different server platforms have different ways of setting HTTP headers, and choosing the right approach ensures your CSP protections reach every visitor.
Think of setting CSP headers like installing a security system at different types of buildings—the protection is the same, but the installation process differs whether you're working with a house (Node.js), an office building (Apache), or a warehouse (Nginx).
Node.js (Express)
In Node.js applications using Express, set headers with middleware:
app.use((req, res, next) => {
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; script-src 'self' 'nonce-xyz123'; style-src 'self'"
);
next();
});
Apache (.htaccess or config)
For Apache servers, add to your .htaccess or virtual host configuration:
Header set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'"
Nginx (server block)
In Nginx configuration files, use the add_header directive:
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'" always;
The always keyword ensures the header is sent even on error responses.
Important Considerations
Each environment requires proper syntax—quotes must be escaped or formatted correctly. Test your configuration after deployment to ensure headers appear in browser DevTools. Remember that server restarts or reloads are typically required for changes to take effect.
Key Takeaway: CSP headers must be configured at the server level using platform-specific syntax—middleware in Node.js, directives in Apache, or add_header in Nginx—to ensure every response includes your security policy.