Next.js Security

Security Best Practices

CSP, CORS, CSRF protection, input validation, and secure headers.

Advertisement

Security Best Practices

CSP, CORS, CSRF protection, input validation, and secure headers.

Overview

Security is critical for protecting user data and preventing attacks.

Key Concepts

  • Content Security Policy — Restrict resource loading
  • CORS — Control cross-origin requests
  • CSRF Protection — Prevent cross-site request forgery
  • Input Validation — Sanitize all user input
  • Secure Headers — HTTP security headers

Code Examples

// next.config.js
const securityHeaders = [
  { key: 'X-Frame-Options', value: 'DENY' },
  { key: 'X-Content-Type-Options', value: 'nosniff' },
  { key: 'Referrer-Policy', value: 'origin-when-cross-origin' },
  {
    key: 'Content-Security-Policy',
    value: "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"
  }
];

module.exports = {
  async headers() {
    return [{
      source: '/:path*',
      headers: securityHeaders
    }];
  }
};

// Input validation
import { z } from 'zod';

const userSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2).max(50),
  age: z.number().int().min(13).max(120)
});

export async function POST(request) {
  const body = await request.json();
  
  const result = userSchema.safeParse(body);
  if (!result.success) {
    return NextResponse.json(
      { error: result.error.issues },
      { status: 400 }
    );
  }

  // Safe to use result.data
  const user = await db.users.create({ data: result.data });
  return NextResponse.json({ data: user });
}

// CSRF protection
// lib/csrf.js
import crypto from 'crypto';

export function generateToken() {
  return crypto.randomBytes(32).toString('hex');
}

export function verifyToken(token, secret) {
  const hmac = crypto.createHmac('sha256', secret);
  hmac.update(token);
  return hmac.digest('hex') === token;
}

Practice

Implement comprehensive security measures for a Next.js application.