How to Secure a Next.js Application in 2026
Next.js apps expose API routes, server actions, and dynamic pages that need specific security treatment. Here's a complete guide to hardening a Next.js application.
Security headers in next.config.ts
Configure the headers() function in next.config.ts to set Content-Security-Policy, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy, and Permissions-Policy on every response. This is the single highest-value change for most Next.js applications.
Rate limiting API routes
API routes without rate limiting are vulnerable to brute force and abuse. Implement sliding-window rate limiting per IP on all mutation endpoints — especially auth, signup, and payment routes. Use an in-process store for single instances, Redis for multi-instance deployments.
CSRF protection for server actions
Next.js 15+ server actions include CSRF protection via the Origin header check. For older versions or custom API routes, validate the Origin header matches your domain on all state-changing requests.
Scan your Next.js app for free.
UebGuard checks your Next.js application for every misconfiguration in this guide — automatically.
No credit card required. Results in 10 seconds.
Input validation with Zod
Never trust request bodies from API routes. Validate every input with Zod schemas before touching your database. Include max-length constraints to prevent ReDoS and memory exhaustion.
Environment variable security
Never expose server-only secrets to the client bundle. Only variables prefixed with NEXT_PUBLIC_ are included in client-side code. Audit your env usage regularly with a linter rule.
Dependency auditing
Run npm audit as part of your CI pipeline. Enable Dependabot or Renovate for automatic dependency PRs. The log4j incident showed that supply chain vulnerabilities can be existential — automate this.
Scan your Next.js app for free.
UebGuard checks your Next.js application for every misconfiguration in this guide — automatically.
No credit card required. Results in 10 seconds.