惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
U
Unit 42
GbyAI
GbyAI
M
MIT News - Artificial intelligence
美团技术团队
罗磊的独立博客
雷峰网
雷峰网
量子位
博客园 - 【当耐特】
Last Week in AI
Last Week in AI
D
Docker
小众软件
小众软件
S
SegmentFault 最新的问题
Blog — PlanetScale
Blog — PlanetScale
阮一峰的网络日志
阮一峰的网络日志
宝玉的分享
宝玉的分享
T
Tailwind CSS Blog
WordPress大学
WordPress大学
V
V2EX
博客园_首页
腾讯CDC
The Cloudflare Blog
A
About on SuperTechFans
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Safely Allow Inline Scripts Without Breaking Secur...
Jakub Andrze · 2026-04-27 · via DEV Community

When building modern web applications, security is not optional. One of the most important protections you can add is a Content Security Policy (CSP).

But here’s the catch:

👉 CSP often blocks inline scripts and styles — which can break your app.

So how do you keep your app secure without disabling useful features?

That’s where CSP nonce comes in - it allows you to safely execute inline code without opening security holes.

In this article, we’ll explore:

  • What CSP nonce is
  • What problem it solves
  • How to implement it
  • How it works automatically in Nuxt with nuxt-security
  • Best practices and common pitfalls

Let’s dive in.

🤔 What Is CSP Nonce?

A nonce (short for number used once) is a unique, random value generated for each request.

It is used in CSP to explicitly allow trusted inline scripts or styles.

Example:

<script nonce="abc123">
  console.log('Secure inline script')
</script>

Enter fullscreen mode Exit fullscreen mode

And in your HTTP headers:

Content-Security-Policy: script-src 'nonce-abc123'

Enter fullscreen mode Exit fullscreen mode

The browser will only execute scripts that have a matching nonce.

CSP nonce is a whitelist mechanism:

  • Only scripts with the correct nonce are allowed
  • Everything else is blocked
  • The nonce changes on every request

This makes it extremely effective against XSS (Cross-Site Scripting) attacks.

CSP nonce is commonly used for:

  1. SSR frameworks - Injecting initial state, Hydration scripts
  2. Analytics / tracking snippets - Inline scripts required by providers
  3. Critical inline scripts - Small scripts needed before app bootstraps

🟢 What Problem Does CSP Nonce Solve?

Without nonce, you usually face a trade-off:

❌ Allow inline scripts (unsafe)

Content-Security-Policy: script-src 'unsafe-inline'

Enter fullscreen mode Exit fullscreen mode

Problem:

  • Opens the door to XSS attacks
  • Any injected script can run

❌ Block inline scripts completely

Content-Security-Policy: script-src 'self'

Enter fullscreen mode Exit fullscreen mode

Problem:

  • breaks inline event handlers
  • breaks injected scripts (SSR hydration, state)
  • breaks some frameworks

🟢 How to Implement CSP Nonce

The process is relatively simple but let's break it down and explain each step individually.

Step 1: Generate a nonce per request

Example (Node.js):

import crypto from 'crypto'

function generateNonce() {
  return crypto.randomBytes(16).toString('base64')
}

Enter fullscreen mode Exit fullscreen mode

Step 2: Add it to response headers

const nonce = generateNonce()

res.setHeader(
  'Content-Security-Policy',
  `script-src 'nonce-${nonce}'`
)

Enter fullscreen mode Exit fullscreen mode

Step 3: Inject it into your HTML

<script nonce="{{nonce}}">
  window.__INITIAL_STATE__ = {}
</script>

Enter fullscreen mode Exit fullscreen mode

⚠️ Critical rule

The nonce in the header and HTML must match exactly. Otherwise, script will be blocked and app may break silently.

🟢 CSP Nonce in Nuxt (with nuxt-security)

If you’re using Nuxt, things get much easier thanks to nuxt-security module that can:

  • Automatically generate nonce per request
  • Inject it into CSP headers
  • Attach it to scripts/styles

It makes it much easier to work with CSP nonces in Nuxt. Let's take a look at the following configuration:

export default defineNuxtConfig({
  modules: ['nuxt-security'],
  security: {
    headers: {
      contentSecurityPolicy: {
        'script-src': [
          "'self'",
          "'nonce-{{nonce}}'"
        ]
      }
    }
  }
})

Enter fullscreen mode Exit fullscreen mode

What happens automatically:

  • Nuxt generates a nonce per request
  • Replaces {{nonce}} in headers
  • Applies nonce to inline scripts

You don’t need to manually wire everything

You can read more here:
https://nuxt-security.vercel.app/

🟢 Common Mistakes

Let's take a look at the list of common mistakes to understand what to look for:

  1. ❌ Reusing the same nonce - Nonce must be unique per request and cryptographically random
  2. ❌ Forgetting to apply nonce in HTML - if you only set CSP header the scripts will still be blocked
  3. ❌ Mixing nonce with unsafe-inline - script-src 'unsafe-inline' 'nonce-abc'
  4. ❌ Caching issues - if HTML is cached nonce may not match header

🧪 Best Practices

  • Generate nonce per request
  • Use secure randomness (crypto)
  • Never reuse nonce
  • Avoid unsafe-inline
  • Use frameworks/tools (like nuxt-security)
  • Test CSP in report-only mode first
  • Monitor browser console for CSP violations

📖 Learn more

If you would like to learn more about Vue, Nuxt, JavaScript or other useful technologies, checkout VueSchool by clicking this link or by clicking the image below:

Vue School Link

It covers most important concepts while building modern Vue or Nuxt applications that can help you in your daily work or side projects 😉

🧪 Advance skills

A certification boosts your skills, builds credibility, and opens doors to new opportunities. Whether you're advancing your career or switching paths, it's a smart step toward success.

Check out Certificates.dev by clicking this link or by clicking the image below:

Certificates.dev Link

Invest in yourself—get certified in Vue.js, JavaScript, Nuxt, Angular, React, and more!

✅ Summary

CSP nonce is a powerful mechanism that allows you to safely use inline scripts while maintaining strong security.

In this article, you learned:

  • What CSP nonce is and how it works
  • What problem it solves (security vs flexibility)
  • How to implement it step by step
  • How Nuxt + nuxt-security handle it automatically
  • Common mistakes and best practices

Take care!
And happy coding as always 🖥️