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

Security Best Practices

Web Foundations🟒 Free Lesson

Advertisement

Security Best Practices

XSS prevention, content security policy, secure forms, and data protection.

Overview

Web security protects users and data from attacks.

Key Concepts

  • XSS Prevention β€” Sanitize user input
  • Content Security Policy β€” Restrict resource loading
  • Secure Forms β€” CSRF protection
  • HTTPS β€” Secure communication
  • Input Validation β€” Client and server validation

Code Examples


<meta http-equiv="Content-Security-Policy" 
  content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'">


<form action="/submit" method="POST">
  <input type="hidden" name="_csrf" value="csrf-token-here">
  <input type="text" name="username" required pattern="[a-zA-Z0-9]{3,20}">
  <input type="email" name="email" required>
  <button type="submit">Submit</button>
</form>

<script>
// XSS prevention
function sanitizeInput(input) {
  const div = document.createElement('div');
  div.textContent = input;
  return div.innerHTML;
}

// Secure DOM manipulation
function safeSetHTML(element, content) {
  element.textContent = content; // Safe - no HTML parsing
}

// For trusted HTML only
function setTrustedHTML(element, html) {
  // Only use with trusted content
  element.innerHTML = html;
}

// CSRF token generation
function generateCSRFToken() {
  const array = new Uint8Array(32);
  crypto.getRandomValues(array);
  return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}

// Secure cookie settings
document.cookie = `session=${token}; Secure; HttpOnly; SameSite=Strict; Path=/`;

// Input validation
function validateEmail(email) {
  const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return regex.test(email);
}

function validatePassword(password) {
  // At least 8 chars, 1 uppercase, 1 lowercase, 1 number
  const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
  return regex.test(password);
}

// Prevent clickjacking
if (window.top !== window.self) {
  window.top.location = window.self.location;
}
</script>

Practice

Implement CSP headers and input sanitization for a form.

⭐

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 Web Development Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement