
Next.js Security Best Practices That Actually Matter in 2025
Practical Next.js security best practices covering headers, CSP, env vars, API routes, and middleware, with real config examples for developers and agencies.
Next.js makes a lot of security decisions for you by default, but it doesn't make all of them. Server components, API routes, middleware, and the App Router all introduce their own attack surface, and most teams only find out something was misconfigured after a client asks why their site got a D on a security scan. Here's what actually matters, with configuration you can copy into your project today.
1. Lock Down HTTP Security Headers
Next.js does not ship with strong security headers out of the box. You have to add them yourself in next.config.js. This is the single biggest quick win for most Next.js apps.
// next.config.js
const securityHeaders = [
{ key: 'X-Frame-Options', value: 'DENY' },
{ key: 'X-Content-Type-Options', value: 'nosniff' },
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
{ key: 'Permissions-Policy', value: 'camera=(), microphone=(), geolocation=()' },
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains; preload' },
];
module.exports = {
async headers() {
return [
{
source: '/:path*',
headers: securityHeaders,
},
];
},
};
If you're deploying on Vercel, these headers apply at the edge for every route automatically. On other hosts (self-managed Node, Docker, etc.), double-check that your reverse proxy (Nginx, Caddy) isn't stripping or overriding them.
Why this matters more than people think
- X-Frame-Options and frame-ancestors in CSP stop clickjacking attacks where your site gets embedded in a malicious iframe.
- HSTS prevents downgrade attacks by forcing browsers to only ever connect over HTTPS, even if someone types
http://. - Missing headers are one of the most common things that drag down a security grade on scanners like WebSentry, even when the actual application code is solid.
2. Write a Content Security Policy That Doesn't Break Your App
CSP is the header developers avoid because it's genuinely annoying to get right with Next.js, especially with inline scripts from third-party analytics or styled-jsx. But an app with no CSP has no defense against injected scripts if an XSS hole ever opens up.
Start with a nonce-based policy using middleware so you don't have to allowlist every script manually:
// middleware.ts
import { NextResponse } from 'next/server';
export function middleware(request) {
const nonce = Buffer.from(crypto.randomUUID()).toString('base64');
const csp = `
default-src 'self';
script-src 'self' 'nonce-${nonce}' 'strict-dynamic';
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self';
connect-src 'self' https://api.yourservice.com;
frame-ancestors 'none';
`.replace(/s{2,}/g, ' ').trim();
const response = NextResponse.next();
response.headers.set('Content-Security-Policy', csp);
response.headers.set('x-nonce', nonce);
return response;
}
Then pull the nonce into your <Script> tags via headers() in a server component. Yes, it's extra work. Run a scan afterward (WebSentry checks your live CSP against known bypass patterns) to confirm you haven't left a wildcard or unsafe-eval sitting in there by accident.
3. Stop Leaking Secrets Through Environment Variables
This is the most common Next.js mistake, full stop. Any environment variable prefixed with NEXT_PUBLIC_ gets bundled into client-side JavaScript. It is not a secret once it's in that bundle.
Rules to actually follow
- Never prefix API keys, database URLs, or signing secrets with
NEXT_PUBLIC_, even "just for testing." - Audit your
.envfiles regularly. Grep forNEXT_PUBLIC_and check each one belongs on the client. - Use server-only environment variables for anything sensitive, and access them exclusively inside API routes, Server Actions, or server components.
- Add
.env*to.gitignorebefore your first commit, not after you push a Stripe secret key to GitHub.
4. Harden API Routes and Route Handlers
Every file in app/api/ or pages/api/ is a public endpoint the moment it's deployed. Treat each one like it will be hit directly by an attacker, because it will.
- Validate everything. Use Zod or similar to parse request bodies before touching them. Don't trust
req.bodyshapes. - Rate limit sensitive routes. Login, password reset, and contact form endpoints are prime targets for brute force and spam. Use a middleware-based limiter (Upstash Ratelimit works well with edge middleware) rather than relying on your hosting provider's default.
- Check the HTTP method explicitly. App Router route handlers export named functions (
GET,POST), so unused methods already 405 by default, but double-check you haven't accidentally exported a catch-all handler that processes any method the same way. - Never trust client-supplied IDs for authorization. If a route handler reads
userIdfrom the request body instead of the session, you've built an IDOR vulnerability.
5. Get CORS Right (Most Teams Get It Wrong)
A common anti-pattern: setting Access-Control-Allow-Origin: * on an API route because a CORS error popped up during development, then shipping it to production. That header combined with credentials enabled is a serious misconfiguration.
// Good: explicit allowlist
const allowedOrigins = ['https://yourapp.com', 'https://app.yourapp.com'];
export async function GET(request) {
const origin = request.headers.get('origin');
const headers = new Headers();
if (allowedOrigins.includes(origin)) {
headers.set('Access-Control-Allow-Origin', origin);
}
// ... rest of handler
}
Never combine a wildcard origin with Access-Control-Allow-Credentials: true. Browsers block this combination for good reason, and if you're seeing it work, something downstream is misconfigured.
6. Secure Cookies and Session Handling
- Set
httpOnly: trueon session cookies so client-side JavaScript can't read them, even through an XSS vector. - Use
secure: truein production so cookies only transmit over HTTPS. - Set
sameSite: 'lax'or'strict'depending on whether you need cross-site navigation to carry the session. Default to'lax'unless you have a specific reason not to. - If you're using NextAuth.js or Auth.js, review the default cookie config rather than assuming it's production-ready out of the box, particularly around the
__Secure-and__Host-cookie name prefixes.
7. Check DNS and TLS Configuration, Not Just Application Code
Application-level security means little if your DNS records or SSL setup are weak. Missing CAA records, outdated TLS versions, or a certificate that doesn't cover all subdomains all affect your real-world risk and, increasingly, your SEO and trust signals too.
This is where it's worth running your domain through a scanner that checks infrastructure alongside application headers. WebSentry grades SSL configuration, DNS records, cookie flags, and CSP together, which is useful because these issues often get missed when teams only audit their own Next.js code and never look at the platform layer underneath it.
8. Keep Dependencies and Middleware Lean
- Run
npm auditorpnpm auditas part of CI, not as an occasional manual check. - Pin dependency versions in lockfiles and review Dependabot or Renovate PRs before merging, don't auto-merge blindly.
- Audit third-party scripts (analytics, chat widgets, ad tags) since each one is a potential script-injection vector that your CSP needs to account for.
- Remove unused middleware. Every function running on every request is additional attack surface and additional latency.
Once you've worked through headers, CSP, env vars, and cookie flags, the fastest way to confirm you haven't missed anything is to run the live site through an external check rather than relying on local config review. Head to websentry.dev and run a free scan. It checks SSL, headers, CSP, cookies, DNS, and CORS in one pass and gives you an A-F grade, so you can see exactly what an outside observer (or an attacker) would see when they hit your Next.js app.
Check your own site
Run a free security scan and see if your site has the issues covered in this article. Results in under 30 seconds.