Web Security Essentials — Protect Your Applications

Learn essential web security: XSS, CSRF, SQL injection, authentication vulnerabilities, and how to protect your apps.

General Intermediate 📖 10 min

Cross-Site Scripting (XSS)

XSS attacks inject malicious scripts into web pages viewed by other users.

// VULNERABLE: Never use innerHTML with user input
element.innerHTML = userInput;

// SAFE: Use textContent
element.textContent = userInput;

// In React: JSX auto-escapes, but be careful with dangerouslySetInnerHTML
// Never use dangerouslySetInnerHTML with user-generated content

Cross-Site Request Forgery (CSRF)

// Use CSRF tokens in forms
<form method="POST" action="/api/transfer">
  <input type="hidden" name="_csrf" value={csrfToken} />
  <input name="amount" />
  <button type="submit">Transfer</button>
</form>

// In Express: use csurf middleware
const csurf = require('csurf');
app.use(csurf({ cookie: true }));

SQL Injection Prevention

// VULNERABLE
const query = 'SELECT * FROM users WHERE id = ' + userId;

// SAFE: Use parameterized queries
const query = 'SELECT * FROM users WHERE id = ?';
db.query(query, [userId]);

// Or use an ORM like Sequelize or Mongoose

Security Headers

// Use helmet in Express
const helmet = require('helmet');
app.use(helmet());

// Content Security Policy
app.use(helmet.contentSecurityPolicy({
  directives: {
    defaultSrc: ["'self'"],
    scriptSrc: ["'self'", "'unsafe-inline'"],
    styleSrc: ["'self'", "'unsafe-inline'"]
  }
}));

Password Security

  • Hash passwords with bcrypt (cost factor >= 12)
  • Never store plain-text passwords
  • Enforce strong password requirements
  • Implement rate limiting on login attempts
  • Use multi-factor authentication

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →