A comprehensive guide to securing your Next.js application. Covering 12 vulnerability categories with framework-specific code examples and best practices.
Use Server Components for data fetching to keep secrets off the client bundle. Only `NEXT_PUBLIC_` prefixed env vars are exposed to the browser.
Enable strict Content Security Policy headers in `next.config.js` using the `headers()` function. Block inline scripts and restrict allowed origins.
Validate all Server Action inputs with Zod or a similar schema validator. Server Actions are public HTTP endpoints -- treat them like API routes.
Use `next/headers` to access cookies securely in Server Components. Never parse cookies manually from request headers.
Configure `images.remotePatterns` in `next.config.js` to allowlist trusted image domains and prevent SSRF through the image optimization API.
Implement middleware-based authentication checks for protected routes using `NextResponse.redirect()` rather than client-side guards alone.
Use the built-in CSRF protection in Server Actions. For custom API routes, implement CSRF tokens manually or use the Origin header check.
Set `poweredByHeader: false` in `next.config.js` to remove the `X-Powered-By: Next.js` header that helps attackers fingerprint your stack.
Cross-Site Scripting (XSS)
A03:2021 - Injection · CWE-79
Cross-Site Request Forgery (CSRF)
A01:2021 - Broken Access Control · CWE-352
Insecure Direct Object References (IDOR)
A01:2021 - Broken Access Control · CWE-639
Sensitive Data Exposure
A02:2021 - Cryptographic Failures · CWE-200
JWT Vulnerabilities
A07:2021 - Identification and Authentication Failures · CWE-347
Server-Side Request Forgery (SSRF)
A10:2021 - Server-Side Request Forgery · CWE-918
File Upload Vulnerabilities
A04:2021 - Insecure Design · CWE-434
Automatically test your Next.js application for all 12 vulnerability categories. Get actionable results in minutes.
Start Free Scan