neha sharma

JavaScript Security: Protecting Your Web Applications

4 min readtech

JavaScript powers most of the web today, but its dynamic nature makes it a frequent target for attacks. Whether you're building a single-page app or managing a large-scale platform, understanding JavaScript security is essential to protect your users and data. Today we are going to learn about JavaScript Security.

Image description

🔐 Why JavaScript Security Matters

  • JavaScript runs on the client-side and can be manipulated by attackers.
  • Insecure JS code can expose users to data theft, session hijacking, or worse.
  • Security issues can lead to reputational damage and legal consequences.

"Security is not a feature — it’s a mindset. Prevention is always cheaper than the cure."


🦠 XSS (Cross-Site Scripting)

What is it?

XSS allows attackers to inject malicious scripts into trusted websites. These scripts can steal cookies, session tokens, or manipulate the DOM.

Code Example (Vulnerable)

const comment = location.search;
document.body.innerHTML = `<div>${comment}</div>`; // Dangerous!

Solution

  • Always escape or sanitize user input.
  • Use libraries like DOMPurify for sanitization.
import DOMPurify from 'dompurify';
const comment = DOMPurify.sanitize(location.search);
document.body.innerHTML = `<div>${comment}</div>`;

Developer Checklist

  • Never trust user input. Always sanitize, have validations.
  • Use CSP to restrict script sources.
  • Use frameworks that auto-escape (e.g., React, Angular)

🧬 CSRF (Cross-Site Request Forgery)

What is it?

CSRF tricks a logged-in user into performing unwanted actions on another website (e.g., changing password).

Code Example (Attack Scenario)

An attacker sends:

<img src="https://yourbank.com/transfer?amount=1000&to=attacker">

Solution

  • Use SameSite cookies and CSRF tokens
  • Validate origin and referer headers on the backend

Developer Checklist

  • Use "SameSite=Lax|Strict" in cookies
  • Implement CSRF tokens in POST forms
  • Validate headers on sensitive endpoints

🧪 Sandboxing

Sandboxing limits the execution of untrusted code using <iframe sandbox> or CSP.

Code Example

<iframe src="/untrusted.html" sandbox="allow-scripts"></iframe>

Developer Checklist

  • Use sandboxed iframes for third-party content
  • Isolate risky scripts using Workers or iframes

🌐 Secure Context, CSP & CORS

Secure Context

Features like Service Workers, navigator.credentials, and getUserMedia only work in HTTPS.

Content Security Policy (CSP)

CSP helps block inline scripts and unauthorized resources.

Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.example.com;

CORS (Cross-Origin Resource Sharing)

CORS restricts cross-origin AJAX requests.

Access-Control-Allow-Origin: https://yourapp.com

Developer Checklist

  • Enforce HTTPS
  • Set a strict CSP header
  • Configure CORS properly

💣 eval, Function, and with

These constructs allow dynamic code execution and can be exploited if misused.

Code Example (Risky)

eval("alert('Hacked')");

Risks

  • Opens door to XSS
  • Prevents JS engine optimizations
  • Makes code hard to audit

Developer Checklist

  • Avoid eval, Function, and with
  • Use JSON.parse and static logic instead

🧷 Secure Serialization & JSON.parse() Gotchas

Problem

Parsing untrusted JSON can be dangerous if assumptions are made.

Risky Example

const user = JSON.parse('{"__proto__": {"admin": true}}');
console.log(user.admin); // true in some cases! Prototype pollution!

Solution

  • Use Object.create(null) when working with parsed objects
  • Use libraries that mitigate prototype pollution (e.g., "secure-json-parse")

Developer Checklist

  • Sanitize or validate JSON structure
  • Avoid assigning parsed objects directly to app state

Tools you should use:

Summary:

Security Risk What it means?
XSS (Cross-Site Scripting) It's like a sneaky kid writing a bad note on your drawing so others read it and get in trouble.
CSRF (Cross-Site Request Forgery) Imagine someone tricks your friend into giving away your toy without asking you.
Sandboxing It's like playing in your playpen—you can’t mess with stuff outside, and nothing outside can mess with you.
Secure Context, CSP & CORS These are like fences, locks, and rules that only let trusted friends and toys into your playroom.
"eval", "Function", and "with" These are like magic words that can do anything—but if a bad wizard uses them, they cause trouble!
Secure Serialization & JSON.parse() Gotchas It’s like reading a story; if the story has sneaky tricks in it, you might believe something bad.

✅ Final Takeaways for Developers

  • Treat all user input as untrusted.
  • Avoid dynamic code execution (eval, new Function).
  • Use HTTPS, CSP, and CORS headers correctly.
  • Isolate third-party code using sandboxed iframes.
  • Regularly audit your dependencies for vulnerabilities (use npm audit).

Security isn't a destination — it's a continuous journey.

Happy Learning!!