The practical, frontend side of securing a Next.js app — preventing XSS in React, setting HTTP security headers and CORS in next.config, and locking things down with a Content Security Policy.
This is the hands-on, frontend slice of web security — the parts you configure and code in a Next.js app. Comfort with React components and the idea of HTTP requests and response headers is all you need.
Before you start
To practise, install VS Code and Node.js, open VS Code's integrated terminal (Ctrl+`), then scaffold and run a Next.js app with whichever package manager you use:
pnpm
pnpm create next-app@latest my-app
cd my-app
pnpm devnpm
npx create-next-app@latest my-app
cd my-app
npm run devAccept the defaults (App Router, TypeScript). The header and CSP changes go in next.config.ts and proxy.ts at the project root — restart the dev server after editing those.
Preventing XSS
Prevent cross-site scripting (XSS) in a Next.js + React app — how TSX auto-escapes values, the danger of dangerouslySetInnerHTML and how to sanitize, and blocking unsafe URLs.
Security Headers & CORS
Harden a Next.js app with HTTP security headers — set X-Content-Type-Options, X-Frame-Options, Referrer-Policy, HSTS, and Permissions-Policy in next.config, and configure CORS for your route handlers.
Content Security Policy
Add a Content Security Policy to a Next.js app — a simple static policy in next.config, a per-request nonce generated in proxy.ts, reading the nonce in a Server Component, and scoping it with a matcher.