document.writeや element.innerHtmlはXSSになるので使わないほうがいい。
// ユーザー入力 "<h1>Hello</h1><script>alert('XSS!');</script>"
const userInput = "<script>alert('XSS!');</script>";
const container = document.getElementById('container');
// テキストノードを作成
const textNode = document.createTextNode("ようこそ!" + userInput);
// テキストノードを要素に追加
container.appendChild(textNode); // スクリプトは実行されず、文字列としてそのまま表示される
おまけ
npm audit
脆弱性があるpackageを調べてくれる。