TL;DR
BREACH attacks exploit weaknesses in how Single Page Applications (SPAs) handle compressed content. This guide shows you how to protect your SPA by disabling compression for sensitive data, adding random tokens to requests, and using strong Content Security Policies.
What is a BREACH Attack?
BREACH (Browser Reconnaissance and Exfiltration via Adaptive Compression of HTTP) allows attackers to steal information from encrypted web traffic. It works by sending specially crafted requests to the server and analyzing the size of the compressed responses. SPAs are vulnerable if they compress sensitive data before encryption.
How to Prevent BREACH Attacks in Your SPA
- Disable Compression for Sensitive Data: This is the most effective solution. Do not compress content that contains user-specific information like session cookies, personal details or financial data.
- Server Configuration (Example – Nginx): Edit your server configuration file to exclude sensitive routes from compression.
http { gzip on; gzip_types text/plain text/css application/json; gzip_disable "text/html"; # Disable for HTML, which often contains sensitive data. } - Server Configuration (Example – Apache): Use the
mod_headersmodule to control compression. - Add Random Tokens to Requests: This makes it harder for attackers to correlate requests and responses.
- Implementation in JavaScript: Generate a unique, random token on the client-side before each request. Include this token as a header or query parameter.
function generateToken() { return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); } fetch('/api/data', { headers: { 'X-CSRF-Token': generateToken() } }); - Server-Side Verification: Verify the token on the server before processing the request.
- Use Strong Content Security Policy (CSP): CSP helps prevent various attacks, including those that could facilitate a BREACH attack.
- Configure CSP Header: Set appropriate directives to restrict the sources from which your SPA can load resources.
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random_nonce}'; style-src 'self' 'nonce-{random_nonce}'; img-src 'self' data: - Keep Software Updated: Regularly update your server software, frameworks, and libraries to patch security vulnerabilities.
- Monitor for Suspicious Activity: Implement logging and monitoring to detect unusual patterns in traffic that might indicate a BREACH attack attempt.
<FilesMatch ".html$">
Header set Vary Accept-Encoding
Header append Cache-Control no-transform
</FilesMatch>
Testing Your SPA
You can use tools like BREACH (the original proof-of-concept) or online BREACH attack simulators to test your application’s vulnerability.

