javascript / expert
Snippet
SSR-Compatible Security Directives
This expert pattern creates a custom directive for secure HTML rendering that supports both client-side mounting and Server-Side Rendering (SSR). By implementing getSSRProps, Vue can safely render the sanitized content on the server, preventing XSS while maintaining hydration consistency.
snippet.js
1
2
3
4
5
6
7
8
9
10
app.directive('secure-html', {mounted(el, binding) {el.innerHTML = DOMPurify.sanitize(binding.value);},getSSRProps(binding) {return {innerHTML: DOMPurify.sanitize(binding.value)};}});
vue
Breakdown
1
getSSRProps(binding)
Special hook that allows the directive to contribute props during the server-side rendering process.
2
DOMPurify.sanitize(binding.value)
Uses a robust library to strip malicious scripts from the input string before it touches the DOM.