Security
Client-side security is the practice of protecting browser-based JavaScript apps from attacks like cross-site scripting (XSS) and cross-site request forgery (CSRF) by sanitizing input, handling tokens safely, and layering defenses.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
While this online editor runs real JavaScript, some security examples require a browser environment. Download Node.js to run JavaScript on your computer, use your browser's Developer Console (Press F12) to test code snippets, or create a .html file with <script> tags and open it in your browser.
Master XSS prevention, CSRF protection, input sanitization, secure token handling, and defense-in-depth architecture.
What You'll Learn
- XSS prevention techniques
- CSRF token protection
- Input sanitization
- Secure token handling
- Content Security Policy
- Defense-in-depth architecture
Why Client-Side Security Matters
The browser is exposed territory . Anyone can inject HTML, override JavaScript, modify requests, steal tokens, and manipulate the DOM. The only safe approach is to treat all user-controlled input as hostile .
What Attackers Can Do
- Steal session tokens and cookies
- Hijack user accounts
- Inject fake login forms
- Execute actions as the user
- Redirect to malicious sites
- Install keyloggers
Your Defense Goals
- Prevent script injection (XSS)
- Block forged requests (CSRF)
- Sanitize all user input
- Secure token storage
- Implement CSP headers
- Build defense-in-depth
Cross-Site Scripting (XSS) — The #1 Frontend Threat
XSS occurs when malicious script executes inside your page. Even one tiny mistake can compromise your entire application.
Three Types of XSS
- Stored XSS: Malicious script saved in database, shown to all users (comments, profiles)
- Reflected XSS: Script injected via URL parameters, executed immediately
- DOM XSS: JavaScript directly puts user input into DOM without server involvement
HTML Escaping — Your First Line of Defense
Escaping converts dangerous characters into safe HTML entities. This is essential when you must display user content.
DOM-Based XSS — Common in SPAs
DOM XSS happens when JavaScript reads user input (from URLs, forms, storage) and inserts it into the page without sanitization. This is extremely common in React, Vue, and Angular apps.
Cross-Site Request Forgery (CSRF)
CSRF forces a victim's browser to make authenticated requests without their knowledge. If your app uses cookies for authentication, you're vulnerable.
CSRF Defense Layers
- SameSite cookies: SameSite=Strict or Lax
- CSRF tokens: Random value verified on each request
- Origin validation: Check Origin/Referer headers
- Authorization headers: Use Bearer tokens instead of cookies
Input Sanitization — Clean Everything
Any time user input appears in HTML, URLs, DOM, or attributes — it must be sanitized.
Use DOMPurify for production HTML sanitization. It handles SVG attacks, mutation XSS, and edge cases that simple regex cannot.
Advanced XSS Vectors
Even when developers escape <script> tags, attackers exploit less obvious injection points.
Secure Token Handling
Token theft is the ultimate goal of most XSS attacks. Never store sensitive tokens in localStorage — XSS can steal them.
❌ Dangerous Token Storage
- localStorage (XSS can read it)
- sessionStorage (XSS can read it)
- URL parameters (visible in logs)
- Non-HttpOnly cookies (JS can access)
Content Security Policy (CSP)
CSP is a browser-level defense that restricts what scripts can run. Even if an attacker injects a script, CSP can block it from executing.
Defense-in-Depth Architecture
No single mechanism protects a modern app. You need layered security — if one layer fails, others prevent disaster.
Security Best Practices Checklist
🛡️ Security Mastery Summary
- XSS Prevention: Use textContent, escape HTML, sanitize with DOMPurify
- CSRF Protection: Use tokens, SameSite cookies, validate Origin headers
- Input Sanitization: Validate, sanitize, and escape ALL user input
- Token Security: Use HttpOnly cookies, memory storage, short expiry
- CSP: Implement strict Content Security Policy headers
- URL Safety: Validate protocols, prevent open redirects
- Defense-in-Depth: Layer multiple security mechanisms
- Never trust: localStorage, URL params, API responses, cookies
Practice quiz
What does XSS stand for?
- Extended Style Sheets
- XML Server Security
- Cross-Site Scripting
- Cross-Server Sync
Answer: Cross-Site Scripting. XSS is Cross-Site Scripting, where malicious script executes inside your page.
Which is the safe way to display untrusted user input?
- element.textContent = input
- element.innerHTML = input
- eval(input)
- document.write(input)
Answer: element.textContent = input. textContent renders input as plain text, not executable HTML.
What does HTML escaping do?
- Removes all text
- Encrypts the page
- Deletes scripts from disk
- Converts dangerous characters like < and > into safe HTML entities
Answer: Converts dangerous characters like < and > into safe HTML entities. Escaping turns characters like < > & " into entities so they can't form active markup.
What is CSRF?
- A faster fetch API
- Forcing a victim's browser to make authenticated requests without their knowledge
- A CSS framework
- A caching strategy
Answer: Forcing a victim's browser to make authenticated requests without their knowledge. Cross-Site Request Forgery tricks the browser into sending authenticated requests.
Which is a recommended CSRF defense in the lesson?
- CSRF tokens and SameSite cookies
- Store tokens in the URL
- Use eval for validation
- Disable HTTPS
Answer: CSRF tokens and SameSite cookies. CSRF tokens, SameSite cookies, and Origin validation defend against CSRF.
Why should you NOT store sensitive tokens in localStorage?
- It is too slow
- It has no space
- XSS can read it
- It is deprecated
Answer: XSS can read it. localStorage is readable by JavaScript, so an XSS attack can steal the token.
When validating a URL from user input, which protocols should be allowed?
- javascript: and data:
- http: and https: only
- any protocol
- file: only
Answer: http: and https: only. Only allow http/https; reject javascript: and data: which can execute code.
What is Content Security Policy (CSP)?
- A linter rule
- A password manager
- A bundler plugin
- A browser-level defense restricting which scripts can run
Answer: A browser-level defense restricting which scripts can run. CSP is set via HTTP header and restricts script sources, blocking injected scripts.
Which dangerous function should you never call with user input?
- JSON.parse()
- eval()
- Array.map()
- String.trim()
Answer: eval(). eval() executes arbitrary code and must never run untrusted input.
What does defense-in-depth mean for a secure app?
- One strong firewall is enough
- Only validate on the server
- Layer multiple security mechanisms so others hold if one fails
- Encrypt the CSS
Answer: Layer multiple security mechanisms so others hold if one fails. Layered security (validation, sanitization, CSP, tokens) means one failure doesn't doom the app.
Continue this course
- Previous: JSON Deep Dive
- Next: Final Project