The "best way" will depend on on what you're trying to prevent/avoid. +1 to Sebastiaan's comment about checking out CSP headers. Alternately - doing some form of validation and input/output encoding if you're storing or displaying the user-agent string somewhere that it's rendered as HTML (e.g., compare with CVE-2007-0817, reflected XSS in the standard ColdFusion error page via a malicious user-agent string). Alternately - you could probably use XSS WAF rules that checked the User-Agent header (or all request headers) -- although that would probably be useful if you wanted to block vs. sanitize