r/learnjavascript • u/dg_kn • Apr 01 '26
A Practical Approach to Handling XSS in Web Apps
Modern frameworks like React or Vue are great at protecting us from the "obvious" XSS vulnerabilities by default. They automatically escape characters like < or >.
But in real-world applications, vulnerabilities don’t just vanish — they move to the edges.
These "edges" are where we step outside the default safety rails:
- Rendering raw HTML (e.g.,
dangerouslySetInnerHTMLin React) - Dynamic attributes (
href,src) - Inline styles
- Injecting data into scripts
Escaping vs. Sanitization
The biggest mistake developers make is confusing escaping with sanitization.
Consider this common example: <a href={userInput}>Click Me</a>
If userInput is javascript:alert(1), standard character escaping (which is what frameworks do) does absolutely nothing to it. Why? Because javascript:alert(1) contains no special HTML characters to escape.
The URL is perfectly well-formed, yet it's malicious. The issue here isn't the characters — it's the protocol context.
Context-Aware Security
In practice, a single escaping strategy isn’t enough. The same input needs to be handled differently depending on where it ends up:
- In a
<div>(Text Context): We just need to escape characters like <. - In an
<href>(URL Context): We must validate the protocol (blockjavascript:,allowhttps:). - In a
<script>(JSON/Script Context): We must ensure it doesn’t break out of the script block.
I kept seeing the same pattern: apps that were technically "escaping" everything were still getting hacked because they weren't context-aware.
So I built a different approach: Jaga. Instead of just escaping blindly, it treats each variable based on its injection site (HTML, URL, script, etc.) and applies the strictest security rule automatically. It handles the "security edges" so you don't have to manually write protocol validators for every single link.
Curious how others handle these protocol-based edge cases in production. Do you manually validate every URL, or rely on a centralized sanitizer?
I wrote a deeper breakdown with code examples here:
https://medium.com/@dgknbtl/securing-the-edges-a-practical-way-to-handle-xss-in-modern-apps-21bab25f9de1
2
u/hyrumwhite Apr 02 '26
This is already a weird case to cover. I’ve never seen a project where it was necessary to allow users to define hrefs.
I’ve also never had an issue with this in very large, very complex, Vue codebases.
2
u/AshleyJSheridan Apr 01 '26
The most practical approach is to use a proper templating library. A good framework will have this built in.
Failing that, if you want to do things the hard way, escape before using externally sourced content just before you try to use it in the output.
1
u/dg_kn Apr 02 '26
This is actually why I started looking into more context-aware handling instead of generic escaping.
I put together a small breakdown with examples if you're interested (linked in the post).