The Threat Landscape
As JavaScript applications handle increasingly sensitive data, security must be integrated into the development lifecycle. The Open Web Application Security Project (OWASP) maintains a top 10 list of critical vulnerabilities that every developer should understand.
Cross-Site Scripting (XSS)
XSS occurs when an attacker injects malicious scripts into content that is then delivered to a different user. This can be used to steal session cookies or perform actions on behalf of the user.
- Stored XSS: Malicious script is permanently stored on the server (e.g., in a database as a comment).
- Reflected XSS: Script is “reflected” off the web server, typically via a URL parameter.
Mitigation:
- Sanitize Input: Never trust data from the user.
- Encode Output: Use frameworks like React which automatically escape strings in JSX.
- Content Security Policy (CSP): A header that tells the browser which sources of scripts are trusted.
Cross-Site Request Forgery (CSRF)
CSRF is an attack that tricks a logged-in user into performing unwanted actions on a web application where they are authenticated. The attack relies on the fact that browsers automatically include cookies (like session IDs) in requests to the associated domain.
Mitigation:
- CSRF Tokens: Include a unique, secret token in every sensitive request (POST, PUT, DELETE). The server validates the token before processing.
- SameSite Cookies: Set the
SameSiteattribute toStrictorLaxto prevent cookies from being sent on cross-site requests.
Secure Authentication: JWT vs. Sessions
Modern applications often use JSON Web Tokens (JWT) for stateless authentication. A JWT is a signed string containing user claims.
- Storage Consideration: Storing a JWT in
localStoragemakes it vulnerable to XSS. Storing it in an HttpOnly, Secure Cookie is a more robust approach, as JavaScript cannot access HttpOnly cookies.
Injection Vulnerabilities
Injection (like SQL Injection or NoSQL Injection) happens when untrusted data is sent to an interpreter as part of a command or query.
// VULNERABLE
db.collection('users').find({ username: req.body.username });
// If req.body.username is { $gt: "" }, it returns all users
Mitigation: Use ORMs/ODMs (like Prisma or Mongoose) that use parameterized queries or built-in sanitization.
Which cookie attribute is essential for preventing a Cross-Site Scripting (XSS) attack from stealing a session token?
Dependency Auditing
JavaScript projects often depend on thousands of third-party packages. These packages can contain vulnerabilities or even malicious code (“Supply Chain Attacks”).
- Use
npm auditto check for known vulnerabilities in your project’s dependency tree. - Update dependencies regularly using tools like
renovateordependabot.