Security Best Practices

Input Validation

Validate all user input to prevent injection attacks and ensure data integrity.

Output Escaping

Escape output to prevent XSS vulnerabilities, especially when rendering user-generated content.

XSS & CSRF Protection

  • Use secure coding practices to prevent cross-site scripting (XSS).
  • Implement CSRF protection for forms and API requests if applicable.

Secure File Uploads

  • Validate file types and sizes.
  • Store uploads outside public directories when possible.
  • Scan files for malware if possible.

Best Practices

  • Use HTTPS for all production environments.
  • Regularly update dependencies to patch security vulnerabilities.
  • Monitor logs and set up alerts for suspicious activity.
  • Document security conventions for new team members.

Rationale

Security is critical for protecting user data, preventing attacks, and maintaining trust. Always follow best practices for both browser and server-side JavaScript.

Authentication & Authorization

  • Use secure authentication libraries (e.g., Passport.js for Node.js, Firebase Auth for web apps).
  • Store passwords securely (use bcrypt or Argon2 for hashing).
  • Never store plain text passwords or sensitive tokens in code or localStorage.
  • Use role-based access control for sensitive actions.
    
    // Good (Node.js)
    const bcrypt = require('bcrypt');
    const hash = await bcrypt.hash(password, 12);

// Bad user.password = password; // plain text


## Input Validation & Sanitization
- Validate all user input on both client and server.
- Use libraries like validator.js for robust validation.
- Sanitize input to remove unwanted characters and prevent injection.
```js
// Good
import validator from 'validator';
if (!validator.isEmail(email)) throw new Error('Invalid email');

// Bad
if (!email.includes('@')) throw new Error('Invalid email');

Output Escaping

  • Always escape output when rendering user data in the DOM.
  • Use built-in methods or libraries (e.g., DOMPurify) to prevent XSS.
    
    // Good
    const safeHtml = DOMPurify.sanitize(userInput);
    document.body.innerHTML = safeHtml;

// Bad document.body.innerHTML = userInput; // vulnerable to XSS


## XSS & CSRF Protection
- Use Content Security Policy (CSP) headers to restrict script sources.
- For forms, use CSRF tokens (server-side frameworks or custom implementation).
- Avoid inline event handlers and direct DOM manipulation with user data.

## Secure File Uploads
- Validate file types and sizes before accepting uploads.
- Store files outside public directories (Node.js: use /uploads, not /public/uploads).
- Scan files for malware if possible.
- Limit file permissions and access.

## Directory & Hosting Protection
- Restrict access to sensitive files and directories (use .htaccess or server config).
- Set correct file permissions (e.g., 755 for directories, 644 for files).
- Use HTTPS for all environments.
- Monitor logs and set up alerts for suspicious activity.

## Advanced Topics
- Use rate limiting (e.g., express-rate-limit) to prevent abuse.
- Implement API authentication (JWT, OAuth2) for protected endpoints.
- Regularly update dependencies and audit for vulnerabilities (npm audit).
- Document security conventions for new team members.

## Example: Secure Express Route
```js
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 });
app.use('/api/', limiter);

app.post('/login', async (req, res) => {
  // Validate and sanitize input
  // Authenticate user
  // Issue JWT token
});