πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

Security Best Practices

Next.js Security🟒 Free Lesson

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.

⭐

Premium Content

Security Best Practices

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert Next.js Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement