Code Security Essentials: Practical Techniques for Python, Java, and JavaScript
Insecure code is one of the most common gateways for attackers. From hardcoded secrets to misused functions and improper error handling, it’s often the small lapses that lead to massive breaches. Writing secure code isn’t just a bonus skill anymore — it’s a core responsibility of every modern software developer.
Security doesn’t live in a single tool, role, or team. It begins the moment you open your code editor. As the complexity of software increases, so does the surface area for potential attack. And attackers don’t wait for compliance certifications — they look for the weakest line of code.
In this article, we go beyond generic advice and into hands-on, actionable secure coding practices. Whether you’re working in Python, Java, or JavaScript, the principles you’ll learn here will help you write resilient, production-grade code that can withstand today’s threat landscape.
Get Vivian Aranha’s stories in your inbox
Join Medium for free to get updates from this writer.
We’ll cover:
- Practical application of the OWASP Secure Coding Practices Cheat Sheet
- Language-specific patterns and pitfalls in Python, Java, and JavaScript
- Secrets management best practices and secure logging strategies
- Real examples of insecure code and how to refactor it into secure alternatives
The OWASP Secure Coding Practices Cheat Sheet
The OWASP Foundation maintains one of the most trusted resources in application security: the Secure Coding Practices Quick Reference Guide. This cheat sheet is not just theory — it’s a distilled set of controls based on real-world exploit patterns.
Key Categories Covered in the Cheat Sheet:
- Input Validation: Validate all inputs from users, files, APIs, and external systems.
- Output Encoding: Encode outputs based on context to prevent XSS and injection attacks.
- Authentication and Password Management: Enforce strong password policies, MFA, and secure session handling.
- Access Control: Implement deny-by-default authorization checks for every resource.
- Error Handling and Logging: Don’t expose stack traces or sensitive information in error messages.
- Data Protection: Use strong encryption for data in transit and at rest.
- Communication Security: Enforce TLS everywhere.
- System Configuration: Secure file permissions, patch libraries, and disable unnecessary services.
By treating the cheat sheet as a checklist and embedding its principles into your pull request templates, CI/CD gates, and peer review guidelines, you create a sustainable secure coding culture.
Language-Specific Secure Coding Considerations
Let’s break down how common vulnerabilities appear in three major languages: Python, Java, and JavaScript — and how to fix them.
Python
Common Issues:
- Using
eval()orexec()on untrusted input - Hardcoded secrets in scripts or config files
- Insecure deserialization with
pickle - Path traversal via unvalidated filenames
Secure Practices:
- Replace
eval()withast.literal_eval()for safer evaluation - Use
os.path.join()to sanitize paths - Avoid
picklefor any data from user input—usejsoninstead - Store secrets in environment variables or a secure secrets manager
Java
Common Issues:
- Using outdated crypto libraries (e.g., MD5, SHA1)
- Logging sensitive data with SLF4J or Log4j
- Insecure XML processing (XXE)
Secure Practices:
- Use
java.security.SecureRandominstead ofRandom - Configure XML parsers to disable external entity loading
- Use BouncyCastle or Java Crypto Extensions (JCE) with AES-GCM
- Sanitize log messages and implement log masking for sensitive values
JavaScript
Common Issues:
- XSS via DOM manipulation
- Insecure use of
innerHTMLordocument.write() - Leaking tokens or passwords in browser logs or URL fragments
Secure Practices:
- Use templating libraries that auto-escape HTML (e.g., Handlebars)
- Never insert untrusted data directly into the DOM
- Implement Content Security Policy (CSP)
- Validate and sanitize user input using libraries like DOMPurify
Secrets Management and Logging Do’s & Don’ts
The Problem with Hardcoded Secrets
Storing API keys, tokens, or database passwords in source code is a recipe for compromise. Secrets get committed, pushed to repos, and exposed via logs more often than most teams realize.
Best Practices:
- Use environment variables, not
.envfiles in production - Leverage secrets managers: AWS Secrets Manager, HashiCorp Vault, or Doppler
- Rotate secrets regularly and revoke unused tokens
- Use automated secrets scanning tools (e.g., GitLeaks, TruffleHog)
Secure Logging Do’s:
- Log security events: failed logins, unusual access patterns, etc.
- Use correlation IDs to trace behavior without logging personal data
- Redact sensitive fields in logs (e.g., passwords, tokens, PII)
Secure Logging Don’ts:
- Never log passwords or access tokens — even during debugging
- Don’t log full stack traces in production (unless behind secure logging infrastructure)
- Avoid excessive logging that can be used for recon by attackers
Refactoring Insecure Code Patterns
Let’s take a few insecure coding patterns and walk through how to fix them.
Example 1: SQL Injection Vulnerability
# Insecure
query = f"SELECT * FROM users WHERE name = '{username}'"# Secure
cursor.execute("SELECT * FROM users WHERE name = %s", (username,))Example 2: Exposing Sensitive Data in Logs
// Insecure
console.log("Login attempt by user", user.email, "with password", user.password);// Secure
console.log("Login attempt by user", user.email);Example 3: Insecure Random Number Generation
// Insecure
Random rand = new Random();// Secure
SecureRandom rand = new SecureRandom();Example 4: Insecure File Upload Handling
# Insecure
save_path = "/uploads/" + filename# Secure
filename = secure_filename(filename)
save_path = os.path.join("/uploads", filename)Refactoring Principles:
- Replace insecure libraries with battle-tested ones
- Encapsulate security logic (e.g., use a validation wrapper)
- Automate regression tests to ensure fixes don’t break features
Code Is the First Line of Defense
Secure coding isn’t just about tools or frameworks — it’s about mindset and discipline. From understanding OWASP principles to managing secrets and logging responsibly, every keystroke can contribute to a safer product — or a serious liability.
The key is consistency. When secure coding becomes a habit — not just a reaction to audits or breaches — it becomes a strength that scales with your software.
Next time you open your IDE, remember: security doesn’t start when someone finds a bug. It starts with you, right here, in your code.










