🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Next.js Security: Headers, CSRF, XSS, and Input

Next.js SecurityđŸŸĸ Free Lesson

Next.js Security: Headers, CSRF, XSS, and Input

Next.js gives you secure defaults in some places and none in others. The framework escapes interpolated strings in JSX by default, which neutralizes the most common reflected XSS — but a dangerouslySetInnerHTML call, a misconfigured CSP, or a Server Action that trusts its caller reopens the door. Security headers are not applied by the framework either; every production Next.js app must declare its own. This lesson assembles the baseline most applications need: a strict header set in next.config, a Content Security Policy that works with the framework rather than against it, CSRF protection for cookie-authenticated mutations, and schema validation that treats every input as hostile.

Prerequisites

  • !Comfort editing next.config and route handlers
  • !Understanding of cookies and same-origin policy
  • !Familiarity with a schema library such as Zod

What You'll Learn

  • 1Configure security headers project-wide in next.config
  • 2Write a CSP compatible with App Router rendering
  • 3Protect cookie-authenticated mutations from CSRF
  • 4Validate and sanitize every input at the boundary

Headers that cost nothing

A handful of response headers close entire classes of attacks and take five minutes to set. X-Frame-Options denies clickjacking framing; X-Content-Type-Options stops browsers from MIME-sniffing an upload into an executable; a Referrer-Policy limits how much URL detail leaks to third parties; and Permissions-Policy disables browser features your app never uses.

javascript
// 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' },
  { key: 'X-DNS-Prefetch-Control', value: 'on' },
];

/** @type {import('next').NextConfig} */
const nextConfig = {
  async headers() {
    return [
      {
        source: '/:path*',
        headers: securityHeaders,
      },
    ];
  },
};

module.exports = nextConfig;

Apply headers to every path by default and override narrowly. HSTS should arrive only after you have confirmed HTTPS works across the whole domain — the includeSubDomains directive is unforgiving of a forgotten staging host.

A CSP the App Router survives

Content-Security-Policy is the most valuable and most frustrating header: value comes from strictness, but an over-strict policy breaks inline hydration scripts, image optimization, and fonts until the page is unusable. Start report-only, collect violations, then promote.

javascript
// next.config.js — CSP entry within securityHeaders
{
  key: 'Content-Security-Policy',
  value: [
    "default-src 'self'",
    "script-src 'self' 'unsafe-inline' https://va.vercel-scripts.com",
    "style-src 'self' 'unsafe-inline'",
    "img-src 'self' blob: data: https://cdn.example.com",
    "font-src 'self' https://fonts.gstatic.com",
    "connect-src 'self' https://*.example.com",
    "frame-ancestors 'none'",
    "base-uri 'self'",
    "form-action 'self'",
  ].join('; '),
}

'unsafe-inline' in script-src is the concession most teams make while Next.js inlines bootstrap scripts; tightening further requires a nonce-based middleware and is covered in the advanced security lesson. frame-ancestors supersedes X-Frame-Options for modern browsers — keep both during the transition. img-src must list your CDN and the data: scheme or next/image optimization silently fails.

Input validation at every boundary

Server Actions and route handlers both accept arbitrary client payloads. A schema per endpoint, parsed before any database call, converts an untrusted blob into a typed value you can actually use — and produces structured errors for the form to display.

javascript
// lib/validation/user.js
import { z } from 'zod';

export const CreateUserSchema = z.object({
  email: z.string().trim().toLowerCase().email().max(254),
  name: z.string().trim().min(2).max(80).regex(/^[\p{L}\p{M} '.-]+$/u),
  age: z.coerce.number().int().min(13).max(120),
  referral: z.string().uuid().optional(),
});

export function parseCreateUser(payload) {
  const result = CreateUserSchema.safeParse(payload);
  if (!result.success) {
    return {
      ok: false,
      issues: result.error.issues.map((issue) => ({
        field: issue.path.join('.'),
        message: issue.message,
      })),
    };
  }
  return { ok: true, data: result.data };
}
javascript
// app/api/v1/users/route.js
import { NextResponse } from 'next/server';
import { parseCreateUser } from '@/lib/validation/user';
import { createUser } from '@/lib/users';

export async function POST(request) {
  const body = await request.json().catch(() => null);
  const parsed = parseCreateUser(body);

  if (!parsed.ok) {
    return NextResponse.json(
      { error: { code: 'VALIDATION_ERROR', details: parsed.issues } },
      { status: 400 }
    );
  }

  const user = await createUser(parsed.data);
  return NextResponse.json({ data: user }, { status: 201 });
}

Normalization before validation — trimming, lower-casing emails, coercing numeric strings — prevents the classic bug where " Alice " and "alice" create two accounts. For anything rendered back into HTML, escape on output as well; schema validation shapes data, it does not sanitize markup.

XSS where React's escaping stops

React escapes text interpolated into JSX, which neutralizes the majority of injection attacks without any effort from you. The exceptions are the explicit escape hatches, and each one needs a deliberate reason. dangerouslySetInnerHTML passes raw markup through: if any part of that string came from a user, it must pass through an HTML sanitizer with a strict allowlist — tags you expect, attributes you expect, nothing else. Markdown rendering is the same problem wearing a different hat, because the renderer's link and image protocols need disabling to prevent javascript: URLs from surviving the conversion.

The subtler routes to script execution are configuration, not markup. An endpoint that reflects a value into a script tag — a JSON blob embedded in the page — can break out of the string if the serialization does not escape the closing script sequence; use the framework's serialization helpers rather than string concatenation. A subdomain you forgot about that hosts user content can set cookies scoped to the parent domain, which is both a session-riding risk and a reminder that your XSS surface includes every host you control. And a DOM sink such as writing to document.location from an untrusted query parameter executes without React ever entering the picture.

The CSP from earlier in the lesson is the safety net under all of these. Even when a sink is missed in review, a policy that restricts script sources and forbids framing keeps the injected payload from executing. That is why defense in depth is not redundancy: each layer catches what the layer above was never designed to see.

CSRF for cookie-authenticated mutations

If your authentication lives in cookies, the browser attaches them to cross-site requests automatically. A form on an attacker's page posting to your Server Action or API route rides that automatic attachment — that is CSRF. SameSite cookies mitigate most of it; a CSRF token handles the rest, including the cases where a subdomain or a plugin widens the origin story.

javascript
// lib/csrf.js
import crypto from 'crypto';
import { cookies } from 'next/headers';

export async function generateCsrfToken() {
  const token = crypto.randomBytes(32).toString('hex');
  const store = await cookies();
  store.set('csrf-token', token, {
    httpOnly: true,
    sameSite: 'lax',
    secure: process.env.NODE_ENV === 'production',
    path: '/',
  });
  return token;
}

export async function verifyCsrfToken(request) {
  const store = await cookies();
  const expected = store.get('csrf-token')?.value;
  const provided =
    request.headers.get('x-csrf-token') ??
    (await request.clone().formData().catch(() => null))?.get('_csrf');

  if (!expected || !provided || expected !== provided) {
    return false;
  }
  crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(provided));
  return true;
}

Compare with timingSafeEqual rather than === so the check does not leak token prefixes through response timing. Set cookies with httpOnly and sameSite lax — lax still sends the cookie on top-level navigations, which keeps login links working while blocking the cross-site POSTs that matter.

Secrets, cookies, and the environment

Next.js inlines environment variables at build time; anything prefixed NEXT_PUBLIC_ ends up in the client bundle and must be treated as public. Server secrets belong in regular environment variables referenced only from server code. Cookies holding sessions need httpOnly, secure, and an appropriate path — scoping the refresh cookie to /api/auth limits its exposure to every route. Never log tokens, never embed credentials in URLs that land in analytics, and rotate any secret that has ever appeared in a commit message or a client-side bundle.

ControlClient bundleServer only
NEXT_PUBLIC_API_URLYes — public by design—
DATABASE_URLNeverYes
JWT_SECRETNeverYes
Stripe publishable keyYesPaired secret stays server-side

Dependencies as part of the attack surface

Every npm package in the client bundle executes with your application's origin privileges, and every package in the server tree runs with your secrets in reach. Treat additions accordingly: prefer packages with narrow scope and active maintenance over feature-rich ones abandoned two years ago, and audit the tree on a schedule rather than after an advisory makes the news. Automated audit tooling in CI fails builds on known high-severity advisories; the human step is reviewing what a fix would change, since a breaking major upgrade is sometimes the only patched line and the honest answer may be to drop the dependency instead.

Lockfiles deserve the same seriousness. Committing them, installing from them in CI, and reviewing diffs catches the dependency-confusion and typosquatting patterns where a typo'd package name resolves to something you never chose. The installed-package review habit generalizes: if a package starts pulling scripts or postinstall hooks you did not expect, that is the moment to look up what they do.

Common Mistakes

Shipping an over-strict CSP in one shot and breaking the app

Fix: Deploy report-only first, collect violations, then enforce with a documented allowlist.

Relying solely on SameSite for CSRF on cookie auth

Fix: Add a per-session CSRF token compared with timing-safe equality on every mutation.

Validating in the form and trusting the server by association

Fix: Re-validate every payload in the action or route handler; the client check is UX only.

Enabling HSTS includeSubDomains before all subdomains serve HTTPS

Fix: Audit every subdomain first; a single HTTP host will become unreachable.

Best Practices

  • Apply a default header set to all paths and override with intent
  • Normalize input before validating so variants cannot duplicate accounts
  • Treat every NEXT_PUBLIC_ variable as published to the world
  • Review the dependency tree for known advisories as part of CI, not annually

Interview Questions

Q1: Why does script-src usually still need unsafe-inline with Next.js?

The framework inlines hydration bootstrap scripts without nonces by default. Removing the concession requires a nonce-generating middleware applied to every response.

Q2: How does CSRF still matter when SameSite=Lax is set?

Lax cookies ride top-level GET navigations, and some embedding or subdomain scenarios widen the trusted origin set. A per-session token verifies intent on state-changing requests.

Q3: Where does XSS protection actually live in a Next.js app?

In React's default output escaping, in disciplined use of dangerouslySetInnerHTML with sanitization, and in a CSP that limits which scripts can execute at all.

Key Takeaways

  • Security headers are opt-in; every production app should declare its own set.
  • Use a report-only CSP first, then enforce with a reviewed allowlist.
  • Validate every payload at the server boundary with a schema; normalize before checking.
  • Cookie auth needs CSRF tokens in addition to SameSite attributes.
  • NEXT_PUBLIC_ variables are public — keep real secrets on the server and rotate anything leaked.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement