Content Security Policy Headers for PrestaShop
What Content Security Policy Is and Why It Matters
Content Security Policy (CSP) is a security mechanism implemented through HTTP headers that tells the browser exactly which resources are allowed to load on your pages. It prevents cross-site scripting (XSS) attacks, data injection attacks, and other code injection vulnerabilities by giving you granular control over where JavaScript, CSS, images, fonts, frames, and other resources can originate from.
Without CSP, a browser will execute any JavaScript it encounters on your page, regardless of where it came from. If an attacker manages to inject a malicious script (through a vulnerable module, a compromised third-party library, or a stored XSS vulnerability), the browser happily executes it with full access to the page content, including customer data, form inputs, and session cookies.
With CSP, you declare a whitelist of trusted sources. If the browser encounters a resource that does not match the policy, it blocks it and logs a violation. This means that even if an attacker finds a way to inject code into your page, the browser refuses to execute it because it does not come from an approved source.
For PrestaShop stores that handle customer personal information, payment data, and authentication credentials, CSP is a critical security layer. It is not a replacement for fixing vulnerabilities in your code, but it is an effective defense-in-depth measure that limits the damage when a vulnerability exists.
CSP Directives Explained
A Content Security Policy consists of one or more directives, each controlling a specific type of resource. The most important directives for PrestaShop are:
default-src: The fallback directive. If a more specific directive is not set, the browser uses default-src. Setting default-src 'self' means that by default, only resources from your own domain are allowed.
script-src: Controls where JavaScript can be loaded from. This is the most critical directive for XSS prevention. Common values include 'self' (your own domain), specific CDN domains, and analytics domains.
style-src: Controls where CSS can be loaded from. PrestaShop themes and modules frequently use inline styles, which means you may need 'unsafe-inline' unless you implement a nonce-based approach.
img-src: Controls where images can be loaded from. PrestaShop stores often load images from their own domain, CDN domains, and third-party services like Google (for user avatars or Maps).
font-src: Controls where fonts can be loaded from. Google Fonts, Font Awesome CDN, and your own domain are common sources.
connect-src: Controls which URLs can be contacted via JavaScript (AJAX requests, WebSocket connections, EventSource). Payment gateways, analytics endpoints, and your own API endpoints need to be listed here.
frame-src: Controls which domains can be embedded in iframes. Payment gateways like PayPal, Stripe, and Klarna use iframes for their payment forms. YouTube and Vimeo embeds also require frame-src entries.
frame-ancestors: Controls which domains can embed your page in an iframe. Setting frame-ancestors 'self' prevents clickjacking attacks by ensuring your store cannot be embedded in another site's iframe.
object-src: Controls plugin content like Flash. Set this to 'none' because Flash is obsolete and no PrestaShop functionality requires it.
base-uri: Controls which URLs can be used in the <base> element. Set to 'self' to prevent base URI manipulation attacks.
form-action: Controls which URLs forms can submit to. This should include your own domain and any external payment processing endpoints.
Starting with Report-Only Mode
Deploying CSP on a PrestaShop store requires careful preparation because an overly restrictive policy will break functionality. The right approach is to start with report-only mode, which tells the browser to report violations without actually blocking anything.
Instead of using the Content-Security-Policy header, use Content-Security-Policy-Report-Only. This header accepts the exact same directives but only generates reports without enforcing the policy. Your store continues to function normally while you collect data about what would be blocked.
Setting Up Violation Reporting
Add a report-uri directive to your policy that points to an endpoint that collects violation reports. You can use a free service like Report URI (report-uri.com), which provides a dashboard for viewing and analyzing CSP violations, or you can set up your own endpoint.
The browser sends violation reports as JSON POST requests. Each report includes the blocked URI, the directive that was violated, the page where the violation occurred, and other useful debugging information. Collecting these reports for a week or two on a live store gives you a comprehensive picture of all the resources your store loads and where they come from.
Building Your Initial Policy
Using the violation reports from report-only mode, build a whitelist of all legitimate resource sources. Group them by directive type. Your initial policy will likely include:
Your own domain for all resource types. CDN domains (like cdnjs.cloudflare.com, fonts.googleapis.com, fonts.gstatic.com) for scripts, styles, and fonts. Analytics domains (like google-analytics.com, googletagmanager.com, connect.facebook.net) for tracking. Payment gateway domains for scripts, frames, and connections. Chat widget domains if you use live chat. Social media domains for embedded content or share buttons.
Building a CSP for PrestaShop
PrestaShop presents specific challenges for CSP implementation because of its architecture and the modules ecosystem.
Handling Inline Styles and Scripts
PrestaShop core, themes, and many modules use inline styles and inline JavaScript extensively. Inline code is blocked by default in CSP because an attacker who injects content into your page would be injecting inline code. There are three approaches to handling this:
Using 'unsafe-inline': The simplest but least secure approach. Adding 'unsafe-inline' to script-src and style-src allows all inline code, which significantly weakens CSP's XSS protection. For style-src, this is generally acceptable because inline styles pose a much lower security risk than inline scripts. For script-src, avoid 'unsafe-inline' if at all possible.
Using nonces: The recommended approach. A nonce is a random, single-use token generated on each request. You add the nonce to your CSP header (script-src 'nonce-abc123') and to each legitimate inline script tag (<script nonce="abc123">). The browser only executes inline scripts that have the correct nonce. Since the nonce changes on every request and an attacker cannot predict it, injected scripts without the nonce are blocked.
Implementing nonces in PrestaShop requires modifying the theme to add nonce attributes to all inline script tags and creating a mechanism (typically a module or a custom hook) that generates the nonce, adds it to the CSP header, and makes it available to templates. This is a significant implementation effort but provides strong XSS protection.
Using hashes: You can whitelist specific inline scripts by their SHA-256 hash. The browser computes the hash of each inline script it encounters and checks it against the hashes listed in the CSP. This approach works for inline scripts that do not change between requests (static inline scripts), but it is impractical for PrestaShop because many inline scripts include dynamic content like product IDs, prices, and user-specific data that change the hash.
Handling eval and Dynamic Code
Some JavaScript libraries use eval() or new Function() to dynamically create and execute code. CSP blocks these by default. If a module or library requires eval, you must add 'unsafe-eval' to script-src. Common culprits include older versions of jQuery templates, some analytics scripts, and certain payment gateway libraries.
Check your violation reports for entries with eval or inline as the blocked URI. These indicate code that uses dynamic evaluation. Where possible, replace the library with a version that does not use eval. When that is not possible (such as with a third-party payment gateway library you cannot modify), 'unsafe-eval' is the only option.
Third-Party Services
Most PrestaShop stores rely on multiple third-party services, each of which needs to be whitelisted in your CSP. Here are the most common ones and the directives they require:
Google Analytics and Google Tag Manager: These require entries in script-src for www.google-analytics.com, www.googletagmanager.com, and tagmanager.google.com. They also need connect-src entries for www.google-analytics.com and analytics.google.com (for sending tracking data), and img-src entries for www.google-analytics.com (for the tracking pixel). Google Tag Manager is particularly challenging because it dynamically loads scripts from domains you may not know in advance, as the scripts loaded depend on the tags configured in GTM.
PayPal: Requires script-src and frame-src entries for *.paypal.com and *.paypalobjects.com. The exact domains depend on whether you use PayPal Standard, PayPal Express, or the newer PayPal Commerce Platform integration.
Stripe: Requires script-src for js.stripe.com, frame-src for js.stripe.com and hooks.stripe.com, and connect-src for api.stripe.com.
Google Fonts: Requires style-src for fonts.googleapis.com and font-src for fonts.gstatic.com.
YouTube embeds: Require frame-src for www.youtube.com and www.youtube-nocookie.com.
Facebook Pixel and social plugins: Require script-src and connect-src for connect.facebook.net and www.facebook.com, plus img-src for www.facebook.com and *.fbcdn.net.
Live chat widgets (Tidio, Crisp, Intercom, etc.): Each has its own set of domains for scripts, styles, WebSocket connections, and images. Check your violation reports or the provider's documentation for the exact domains required.
A Complete CSP Example for PrestaShop
Here is a realistic CSP header for a PrestaShop store that uses Google Analytics, Google Fonts, PayPal, YouTube embeds, and has inline styles:
Content-Security-Policy: default-src 'self'; script-src 'self' www.google-analytics.com www.googletagmanager.com js.stripe.com 'unsafe-inline' 'unsafe-eval'; style-src 'self' fonts.googleapis.com 'unsafe-inline'; img-src 'self' data: www.google-analytics.com *.paypal.com; font-src 'self' fonts.gstatic.com; connect-src 'self' www.google-analytics.com analytics.google.com api.stripe.com; frame-src 'self' www.youtube.com www.youtube-nocookie.com js.stripe.com *.paypal.com; frame-ancestors 'self'; object-src 'none'; base-uri 'self'; form-action 'self' *.paypal.com;
This policy includes 'unsafe-inline' and 'unsafe-eval' for scripts, which weakens XSS protection but is necessary for most PrestaShop installations that have not been modified to support nonces. For img-src, the data: source is included because PrestaShop and many modules use data URIs for small images and icons.
Implementing CSP in PrestaShop
Via .htaccess (Apache)
For Apache servers, add the CSP header in your .htaccess file. Place it near the top of the file, before the PrestaShop rewrite rules:
Header set Content-Security-Policy "default-src 'self'; script-src 'self' ..."
This requires the mod_headers module to be enabled. You can verify by checking if your server returns the header using browser DevTools (Network tab, click on the main document request, check the Response Headers).
Via Nginx Configuration
For Nginx, add the header in your server block:
add_header Content-Security-Policy "default-src 'self'; script-src 'self' ..." always;
The always parameter ensures the header is sent even for error responses, which is important because error pages can also be targets for XSS attacks.
Via a PrestaShop Module
Implementing CSP through a module gives you the ability to manage the policy from the back office. The module hooks into the actionOutputHTMLBefore or uses PHP's header() function in a front controller hook to add the CSP header to every response. A module-based approach is easier to maintain because you can update the policy without editing server configuration files and without restarting the web server.
Testing Your CSP with Browser DevTools
After implementing your CSP (in report-only mode initially), use browser DevTools to monitor for violations. Open the Console tab and look for messages that start with "[Report Only]" (in report-only mode) or "Refused to" (in enforcement mode). Each message tells you exactly what was blocked and which directive was responsible.
Test every page type on your store: the home page, category pages, product pages, the cart, the checkout process (including each step and each payment method), the customer account pages, and CMS pages. Each page type may load different resources, and you need to ensure your policy covers all of them.
Pay special attention to the checkout process. A blocked payment gateway script or iframe during checkout directly prevents customers from completing purchases. Test every payment method you offer, including the 3D Secure verification flow if applicable, because these often load additional resources from domains that are not obvious.
Common Testing Pitfalls
Testing in a development environment may not reveal all violations because your development setup may not include all the third-party services that run on production (analytics, advertising pixels, live chat, A/B testing tools). Always deploy CSP in report-only mode on production first and collect reports for at least one to two weeks before switching to enforcement.
Some violations only occur under specific conditions. For example, a payment gateway might load additional verification scripts only when a customer's card requires 3D Secure authentication. Social sharing buttons might load scripts only when a visitor clicks them. Dynamic content loaded via AJAX may reference resources that are not present on the initial page load. Run through every possible user flow during testing.
Gradual Enforcement Strategy
The recommended deployment strategy for CSP on PrestaShop follows these steps:
Phase 1: Discovery. Deploy a permissive Content-Security-Policy-Report-Only header with default-src * 'unsafe-inline' 'unsafe-eval' data: blob:; and a report-uri. This logs all resources without blocking anything, giving you a complete inventory of what your store loads.
Phase 2: Draft policy. Based on the violation reports, build a whitelist policy that covers all legitimate resources. Deploy it in report-only mode and monitor for violations that indicate you missed a resource.
Phase 3: Refine. Over one to two weeks, check violation reports daily and add any legitimate sources you missed. Pay attention to reports that come from specific page types or user flows you might not have tested manually.
Phase 4: Enforce. Switch from Content-Security-Policy-Report-Only to Content-Security-Policy. Keep the report-uri directive so you continue receiving violation reports. Monitor closely for the first week after enforcement to catch any legitimate resources that are being blocked.
Phase 5: Tighten. Once enforcement is stable, look for opportunities to tighten the policy. Can you replace 'unsafe-inline' in script-src with nonces? Can you narrow wildcard domains to specific subdomains? Can you remove sources that are no longer used? Each tightening step improves your security posture.
Maintaining Your CSP
A CSP is not a set-and-forget configuration. Every time you install a new module, add a third-party service, change payment gateways, or update your theme, you may need to update your CSP to include new resource sources. Make CSP review part of your module installation and update process.
Keep your report-uri active even after enforcement so you receive alerts about new violations. A sudden increase in violation reports might indicate that a module update introduced new resource requirements, or it might indicate an actual XSS attack attempt that your CSP is successfully blocking. Either way, you want to know about it.
Document your CSP and the reason for each entry. Over time, policies accumulate entries for services you no longer use. Periodic reviews to remove unnecessary entries keep the policy clean and reduce the attack surface. A CSP with fewer allowed sources is inherently more secure than one with many.
Czy ta odpowiedź była pomocna?
Masz jeszcze pytania?
Can't find what you're looking for? Send us your question and we'll get back to you quickly.