There are a couple of ways to secure websites from the vulnerabilities that could lead to an XSS attack:
In WordPress core, plugins, and themes, have all input strictly sanitized as it’s received.
In WordPress core, plugins, and themes, escape all data on output to prevent it from being categorized as active content by applying combinations of HTML, JavaScript and CSS encoding.
Through a site owner, developer, devops engineer or through a third party solution like WordFence or Sucuri, use a Content Security Policy (CSP), a browser security mechanism that can reduce the severity of XSS and other attacks by limiting the resources a page can load.
Make sure your WordPress core, plugins and themes are up-to-date and do not contain vulnerabilities—use third party solutions and hosting security features (alerts and disabling vulnerable components).