Skip to content

Troubleshoot CSP Violations

Learn how to diagnose and fix Content Security Policy (CSP) violations in your Airbase applications.

Symptoms

Your application deploys successfully but:

  • JavaScript doesn't execute
  • Buttons don't respond to clicks
  • Dynamic content doesn't load
  • Charts or visualizations don't render

Step 1: Open Browser Console

The browser console shows all CSP violations.

How to open:

  • Chrome/Edge: Press F12 or Ctrl+Shift+I (Windows) / Cmd+Option+I (Mac)
  • Firefox: Press F12 or Ctrl+Shift+K (Windows) / Cmd+Option+K (Mac)
  • Safari: Enable Developer menu in Preferences, then press Cmd+Option+C

Or: Right-click anywhere on the page → InspectConsole tab


Step 2: Identify CSP Violation Errors

Look for red error messages mentioning "Content Security Policy".

Common CSP Error Messages

Error Type 1: Inline Script

Refused to execute inline script because it violates the following
Content Security Policy directive: 'script-src 'self''. Either the
'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...')
is required to enable inline execution.

What it means: You have inline <script> tags in your HTML.

Error Type 2: Inline Event Handler

Refused to execute inline event handler because it violates the following
Content Security Policy directive: 'script-src 'self''.

What it means: You're using onclick, onload, or similar inline attributes.

Error Type 3: eval() Usage

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not
an allowed source of script in the following Content Security Policy
directive: 'script-src 'self''.

What it means: Your code or a library is using eval() or Function().


Step 3: Locate the Problematic Code

The error message usually includes information about where the violation occurred.

Reading the Error

Refused to execute inline script because it violates...
  at https://myapp.app.tc1.airbase.sg/:25

The :25 indicates line 25 of your HTML file.

Finding Inline Scripts

Search your codebase for:

grep -r "<script>" .
grep -r "onclick=" .
grep -r "onload=" .
grep -r "eval(" .

Step 4: Fix the Violations

Fix: Inline Scripts

❌ Problem:

<script>
  console.log('Hello');
  setupApp();
</script>

✅ Solution:

Create an external file:

<script src="/js/main.js"></script>
// /js/main.js
console.log('Hello');
setupApp();

Fix: Inline Event Handlers

❌ Problem:

<button onclick="handleClick()">Click</button>

✅ Solution:

<button id="myButton">Click</button>
<script src="/js/handlers.js"></script>
// /js/handlers.js
document.getElementById('myButton').addEventListener('click', handleClick);

function handleClick() {
  // Your code here
}

Fix: eval() Usage

❌ Problem:

const result = eval('2 + 2');

✅ Solution:

const result = 2 + 2;

Fix: Dynamic Script Injection

❌ Problem:

element.innerHTML = '<script>doSomething()</script>';

✅ Solution:

// Create elements programmatically
const script = document.createElement('script');
script.src = '/js/module.js';
document.body.appendChild(script);

// Or better: load the script separately and call the function
doSomething();

Step 5: Test the Fix

After fixing violations:

  1. Rebuild your application (if applicable)
  2. Redeploy to Airbase:
    airbase container build
    airbase container deploy --yes staging
    
  3. Clear browser cache: Ctrl+Shift+Delete (or Cmd+Shift+Delete on Mac)
  4. Reload the page: Ctrl+R (or Cmd+R on Mac)
  5. Check console again - violations should be gone

Common Scenarios

Scenario 1: Third-Party Library Violations

Problem: A library you're using generates inline scripts.

Diagnosis:

Refused to execute inline script...
  at https://cdn.example.com/library.js:150

Solutions:

  1. Check library documentation for CSP configuration options
  2. Update to latest version - newer versions may be CSP-compliant
  3. Find alternative library that is CSP-compliant
  4. For Python apps only: See Nginx Proxy Workaround as last resort

Scenario 2: Framework Build Output Issues

Problem: Your framework's build process injects inline scripts.

For Vite/React:

  • Check vite.config.ts for plugins that might inject scripts
  • Ensure you're using production build: npm run build
  • Vite should generate CSP-compliant output by default

For Next.js:

  • Ensure you're on Next.js 13+
  • Check _document.js for custom inline scripts
  • Remove any dangerouslySetInnerHTML with scripts

For Webpack:

  • Check webpack config for plugins
  • Ensure using production mode
  • Consider using csp-html-webpack-plugin

Scenario 3: Template Engine Injecting Scripts

Problem: Server-side templates adding inline scripts.

For Flask/Jinja2:

<!-- ❌ Don't do this -->
<script>
  const config = {{ config|tojson }};
</script>

<!-- ✅ Do this -->
<div id="app" data-config="{{ config|tojson }}"></div>
<script src="/static/js/app.js"></script>
// /static/js/app.js
const configEl = document.getElementById('app');
const config = JSON.parse(configEl.dataset.config);

Scenario 4: Analytics/Tracking Scripts

Problem: Inline analytics code.

❌ Common mistake:

<script>
  gtag('config', 'GA_MEASUREMENT_ID');
</script>

✅ Solution:

<script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>
<script src="/js/analytics.js"></script>
// /js/analytics.js
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');

Scenario 5: Dynamic Content Loading

Problem: Loading content with innerHTML that contains scripts.

❌ Problem:

fetch('/api/content')
  .then(r => r.text())
  .then(html => {
    document.getElementById('container').innerHTML = html;
    // If html contains <script> tags, they won't execute due to CSP
  });

✅ Solution:

// Fetch data as JSON, not HTML
fetch('/api/content')
  .then(r => r.json())
  .then(data => {
    // Create elements programmatically
    const container = document.getElementById('container');
    data.items.forEach(item => {
      const div = document.createElement('div');
      div.textContent = item.text;
      container.appendChild(div);
    });
  });

Special Case: Python Apps with Non-Compliant Libraries

If you're deploying a Python application (Streamlit, Plotly Dash, etc.) that uses libraries generating non-CSP-compliant code, and the library doesn't provide CSP configuration options:

Symptoms:

  • Application deploys but charts/visualizations don't render
  • Console shows CSP violations from library code
  • Library has no CSP settings

Advanced Workaround:

See Nginx Proxy Workaround for Python Apps for a solution that overrides CSP headers.

⚠️ Warning: This weakens security. Only use as a last resort after exhausting all other options.


Debugging Tips

Tip 1: Test Locally with CSP

Before deploying, test with CSP headers locally:

// For Express apps
const helmet = require('helmet');
app.use(helmet.contentSecurityPolicy({
  directives: { scriptSrc: ["'self'"] }
}));

See Test CSP Locally for more details.

Tip 2: Incremental Fixes

If you have many violations:

  1. Fix inline scripts first
  2. Then inline event handlers
  3. Then eval() usage
  4. Test after each fix

Tip 3: Check Framework Documentation

Most modern frameworks have CSP documentation:

Tip 4: Search for Known Issues

Check if others have encountered CSP issues with your libraries:

"library-name" CSP "Content Security Policy"

Prevention

To avoid CSP violations in the future:

Always use external JavaScript filesUse addEventListener for all eventsAvoid eval(), Function(), and similarTest with CSP headers before deployingChoose CSP-compliant libraries

See Write CSP-Compliant Code for complete guidelines.


Still Having Issues?

If you've followed all steps and still have CSP violations:

  1. Share the exact error from browser console
  2. Identify the source: Your code or a library?
  3. Check library version and documentation
  4. Consider alternatives if library is not CSP-compliant
  5. For Python apps: Last resort is Nginx Proxy Workaround

See Also


Summary

Quick debugging steps:

  1. Open browser console (F12)
  2. Look for red CSP error messages
  3. Identify violation type (inline script, event handler, eval)
  4. Find problematic code in your codebase
  5. Fix by moving to external files / using addEventListener
  6. Redeploy and verify in console

Most CSP violations are straightforward to fix once identified!