Home/Blog/Web Application Security: Best Practices Every Developer Must Know
Back to Blog
Web Development

Web Application Security: Best Practices Every Developer Must Know

December 28, 2023
18 min read
Michael Chen
📝

Featured Image Placeholder

Add your blog post image here

SecurityWeb DevelopmentBest PracticesOWASPBackend

Introduction


Security breaches cost companies millions and destroy user trust. As developers, we must build security into our applications from day one. This guide covers essential security practices every developer should implement.


OWASP Top 10 Vulnerabilities


1. Broken Access Control


**The Problem:** Users accessing resources they shouldn't.


Prevention:

  • Implement principle of least privilege
  • Deny by default
  • Use RBAC (Role-Based Access Control)
  • Validate authorization on every request
  • Never trust client-side access controls

  • Example (Node.js):

    ```javascript

    // Bad

    app.get('/admin/users', (req, res) => {

    // No authorization check!

    const users = getAllUsers();

    res.json(users);

    });


    // Good

    app.get('/admin/users', requireAuth, requireRole('admin'), (req, res) => {

    const users = getAllUsers();

    res.json(users);

    });

    ```


    2. Cryptographic Failures


    **The Problem:** Sensitive data exposure due to weak encryption.


    Prevention:

  • Use HTTPS everywhere (TLS 1.3)
  • Hash passwords with bcrypt/argon2
  • Encrypt sensitive data at rest
  • Never store plain-text secrets
  • Use secure key management (AWS KMS, HashiCorp Vault)

  • Password Hashing:

    ```javascript

    const bcrypt = require('bcrypt');

    const saltRounds = 12;


    // Hash password

    const hashedPassword = await bcrypt.hash(password, saltRounds);


    // Verify password

    const isValid = await bcrypt.compare(inputPassword, hashedPassword);

    ```


    3. Injection Attacks


    **The Problem:** SQL, NoSQL, Command injection allowing unauthorized access.


    Prevention:

  • Use parameterized queries (prepared statements)
  • Use ORMs properly (Prisma, TypeORM)
  • Validate and sanitize all inputs
  • Use least privilege database accounts
  • Implement input whitelisting

  • SQL Injection Prevention:

    ```javascript

    // BAD - Vulnerable to SQL injection

    const query = `SELECT * FROM users WHERE email = '${email}'`;


    // GOOD - Parameterized query

    const query = 'SELECT * FROM users WHERE email = ?';

    db.query(query, [email]);

    ```


    4. Insecure Design


    **The Problem:** Architectural flaws in application design.


    Prevention:

  • Threat modeling during design
  • Security requirements in user stories
  • Secure development lifecycle (SDL)
  • Regular security reviews
  • Defense in depth strategy

  • 5. Security Misconfiguration


    **The Problem:** Default configurations, unnecessary features enabled.


    Prevention:

  • Remove default accounts/passwords
  • Disable unnecessary features
  • Keep frameworks/libraries updated
  • Implement proper error handling
  • Use security headers

  • Essential Security Headers:

    ```javascript

    app.use((req, res, next) => {

    res.setHeader('X-Content-Type-Options', 'nosniff');

    res.setHeader('X-Frame-Options', 'DENY');

    res.setHeader('X-XSS-Protection', '1; mode=block');

    res.setHeader('Strict-Transport-Security', 'max-age=31536000');

    res.setHeader('Content-Security-Policy', "default-src 'self'");

    next();

    });

    ```


    6. Vulnerable Components


    **The Problem:** Using outdated or vulnerable dependencies.


    Prevention:

  • Regular dependency updates
  • Use `npm audit` or `snyk`
  • Monitor CVE databases
  • Automated dependency scanning
  • Remove unused dependencies

  • Automation:

    ```bash

    Check for vulnerabilities

    npm audit

    npm audit fix


    Use Snyk

    npx snyk test

    npx snyk monitor

    ```


    7. Authentication Failures


    **The Problem:** Weak authentication allowing unauthorized access.


    Prevention:

  • Implement MFA (Multi-Factor Authentication)
  • Use strong password policies
  • Rate limit login attempts
  • Implement account lockout
  • Use secure session management
  • JWT with proper expiration

  • Secure Session Management:

    ```javascript

    const session = require('express-session');


    app.use(session({

    secret: process.env.SESSION_SECRET,

    resave: false,

    saveUninitialized: false,

    cookie: {

    secure: true, // HTTPS only

    httpOnly: true, // No JavaScript access

    maxAge: 3600000, // 1 hour

    sameSite: 'strict' // CSRF protection

    }

    }));

    ```


    8. Software and Data Integrity Failures


    **The Problem:** Unsigned updates, insecure CI/CD, deserialization.


    Prevention:

  • Verify package signatures
  • Use SRI (Subresource Integrity) for CDN
  • Secure CI/CD pipelines
  • Avoid deserializing untrusted data
  • Implement code signing

  • 9. Security Logging Failures


    **The Problem:** Insufficient logging preventing incident detection.


    Prevention:

  • Log authentication events
  • Log access control failures
  • Log input validation failures
  • Centralized logging (ELK, DataDog)
  • Real-time alerting
  • Never log sensitive data

  • Good Logging Practice:

    ```javascript

    logger.info('User login attempt', {

    userId: user.id,

    ip: req.ip,

    userAgent: req.get('User-Agent'),

    success: true,

    timestamp: new Date()

    });


    // Never log:

    // - Passwords

    // - Credit card numbers

    // - Session tokens

    // - Personal data

    ```


    10. Server-Side Request Forgery (SSRF)


    **The Problem:** Application fetching remote resources without validation.


    Prevention:

  • Whitelist allowed URLs/IPs
  • Disable unused URL schemas
  • Use separate networks for internal services
  • Validate and sanitize URLs
  • Implement network segmentation

  • Additional Security Best Practices


    Input Validation


    Always validate:

  • Length constraints
  • Data type
  • Format (regex)
  • Range limits
  • Whitelist approach

  • ```javascript

    const { z } = require('zod');


    const userSchema = z.object({

    email: z.string().email(),

    age: z.number().int().min(13).max(120),

    username: z.string().min(3).max(20).regex(/^[a-zA-Z0-9_]+$/)

    });


    // Validate

    const result = userSchema.safeParse(userData);

    if (!result.success) {

    return res.status(400).json({ errors: result.error });

    }

    ```


    XSS Prevention


    Cross-Site Scripting prevention:

  • Escape output HTML
  • Use Content Security Policy
  • Sanitize user input
  • Use framework protection (React escapes by default)

  • CSRF Protection


    Cross-Site Request Forgery prevention:

  • Use CSRF tokens
  • SameSite cookies
  • Double submit cookies
  • Custom headers for APIs

  • ```javascript

    const csrf = require('csurf');

    const csrfProtection = csrf({ cookie: true });


    app.post('/transfer', csrfProtection, (req, res) => {

    // Protected endpoint

    });

    ```


    Rate Limiting


    Prevent brute force attacks:

    ```javascript

    const rateLimit = require('express-rate-limit');


    const limiter = rateLimit({

    windowMs: 15 * 60 * 1000, // 15 minutes

    max: 100, // Limit each IP to 100 requests per windowMs

    message: 'Too many requests from this IP'

    });


    app.use('/api/', limiter);

    ```


    File Upload Security


    Safe file uploads:

  • Validate file type
  • Limit file size
  • Scan for malware
  • Store outside web root
  • Generate random filenames
  • Use object storage (S3)

  • API Security


    Secure your APIs:

  • Use API keys/OAuth
  • Rate limiting per key
  • Input validation
  • Output encoding
  • Versioning
  • API gateway

  • Security Testing


    Automated Tools


    Use these tools regularly:

  • OWASP ZAP - Vulnerability scanner
  • Burp Suite - Security testing
  • SonarQube - Code quality/security
  • npm audit - Dependency check
  • Snyk - Security monitoring

  • Manual Testing


    Regular security reviews:

  • Penetration testing
  • Code reviews
  • Security audits
  • Threat modeling
  • Red team exercises

  • Security Checklist


    Before deploying:

  • [ ] HTTPS enabled everywhere
  • [ ] Security headers configured
  • [ ] Input validation implemented
  • [ ] Authentication properly secured
  • [ ] Authorization checked on all endpoints
  • [ ] Secrets in environment variables
  • [ ] Dependencies updated
  • [ ] Error handling doesn't leak info
  • [ ] Logging configured
  • [ ] Rate limiting enabled
  • [ ] CORS properly configured
  • [ ] Database queries parameterized
  • [ ] File uploads secured
  • [ ] Security testing completed

  • Incident Response Plan


    Prepare for breaches:

    1. Detection system in place

    2. Response team identified

    3. Communication plan ready

    4. Backup and recovery procedures

    5. Legal/regulatory compliance

    6. Post-incident review process


    Conclusion


    Security is not a feature—it's a requirement. Implement these practices from day one, keep learning about new threats, and never assume you're "secure enough."


    Key Takeaways


  • Security must be built-in, not bolted-on
  • Follow OWASP Top 10 guidelines
  • Validate and sanitize all inputs
  • Use security headers and HTTPS
  • Keep dependencies updated
  • Implement proper logging and monitoring
  • Regular security testing is essential

  • Need a security audit for your application? [Contact our security experts](/contact).


    M

    Michael Chen

    DevOps Engineer

    Michael specializes in cloud infrastructure and CI/CD pipelines. He helps teams deploy faster and more reliably.

    Share this post:

    Need Expert Help with Your Project?

    Let's discuss how we can help bring your ideas to life.