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

推荐订阅源

有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
N
Netflix TechBlog - Medium
WordPress大学
WordPress大学
罗磊的独立博客
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
A
About on SuperTechFans
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
D
Docker
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
Blog — PlanetScale
Blog — PlanetScale
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
J
Java Code Geeks
博客园 - 聂微东
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
美团技术团队
小众软件
小众软件
Stack Overflow Blog
Stack Overflow Blog
C
Check Point Blog

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
Bulletproof React: Strict Content Security Policies in Ne...
Prajapati Pa · 2026-05-12 · via DEV Community

The Danger of Inline Scripts

Cross-Site Scripting (XSS) remains one of the most critical vulnerabilities in modern web applications. If an attacker manages to inject a malicious script into your B2B SaaS platform—perhaps through an unescaped comment forum or a compromised third-party NPM package—they can hijack user sessions, steal HttpOnly cookies, and deface your application.

React automatically escapes text output, which provides baseline protection. However, if you rely on third-party analytics, marketing scripts, or dangerously set inner HTML, your Next.js application is still vulnerable. To build an impenetrable frontend at Smart Tech Devs, we must implement a Strict Content Security Policy (CSP) with Nonces.

What is a Strict CSP?

A Content Security Policy is an HTTP header sent by your server that tells the browser exactly which scripts, images, and styles are allowed to execute. A Strict CSP takes this further by rejecting all inline scripts unless they carry a unique, cryptographically secure string called a "nonce" (Number Used Once), generated fresh on every single page load.

If a hacker injects <script>stealData()</script>, the browser will block it entirely because the script lacks the server-generated nonce for that specific HTTP request.

Architecting CSP Nonces in Next.js Middleware

To implement this in the Next.js App Router, we use Edge Middleware to generate the nonce, append it to the CSP header, and pass it down to our React components.

Step 1: Generating the Nonce in Middleware


// middleware.ts
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
    // 1. Generate a random, cryptographically secure Base64 string
    const nonce = Buffer.from(crypto.randomUUID()).toString('base64');

    // 2. Define the Strict CSP Policy
    // We strictly allow our own domain and scripts that carry the exact nonce
    const cspHeader = `
        default-src 'self';
        script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
        style-src 'self' 'nonce-${nonce}';
        img-src 'self' blob: data:;
        font-src 'self';
        object-src 'none';
        base-uri 'self';
        form-action 'self';
        frame-ancestors 'none';
        upgrade-insecure-requests;
    `.replace(/\s{2,}/g, ' ').trim();

    // 3. Clone the request headers and append the CSP and the Nonce
    const requestHeaders = new Headers(request.headers);
    requestHeaders.set('x-nonce', nonce);
    requestHeaders.set('Content-Security-Policy', cspHeader);

    // 4. Return the response with the strict headers attached
    const response = NextResponse.next({
        request: {
            headers: requestHeaders,
        },
    });

    response.headers.set('Content-Security-Policy', cspHeader);
    return response;
}

Step 2: Consuming the Nonce in the Root Layout

Now that the middleware has attached the nonce to the request headers, we must read it in our root layout.tsx and apply it to Next.js's internal script injection.


// app/layout.tsx
import { headers } from 'next/headers';
import Script from 'next/script';

export default function RootLayout({ children }: { children: React.ReactNode }) {
    // Retrieve the nonce securely generated by the middleware
    const nonce = headers().get('x-nonce') || '';

    return (
        <html lang="en">
            <body>
                {children}

                {/* Example of a verified third-party script using the nonce */}
                <Script 
                    src="https://trusted-analytics.com/script.js" 
                    strategy="afterInteractive"
                    nonce={nonce} 
                />
            </body>
        </html>
    );
}

The Engineering ROI

Implementing a Strict CSP is the hallmark of enterprise frontend security. It acts as an absolute fail-safe. Even if a developer makes a mistake and introduces an XSS vulnerability into a React component, the browser itself will refuse to execute the malicious code. Security by design means eliminating entire classes of vulnerabilities at the architectural level.