Home > Enterprise >  How to sanitize user input string in nodejs, before injecting it in a template engine or say simple
How to sanitize user input string in nodejs, before injecting it in a template engine or say simple

Time:02-14

I have webpages (basically business cards) whose titles are created based on user inputs. I am planning to use simple JS template string for this purpose, instead of some template engine. (I am using express.js/node.js for this purpose)

response.send(`
<html>

 <head>
  <title>${user_inputed_title_got_from_DB}</title>
  <meta property="og:title" content="${some_more_user_content}" />
 </head>

 <body>
  <script>
     window.location.href="/business-card/${user_input_number}";
  </script>
 </body>

</html>`)

How to avoid XSS injection from a malacious user?

CodePudding user response:

For normal HTML tags, this answer should suffice:

function escapeHtml(unsafe)
{
    return unsafe
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

However, your redirect in the script tag needs to be treated a bit more carefully. One common approach is to put the redirect in an attribute, which can be escaped with the above function:

<script data-redir="/business-card/${escapeHtml(user_input_number)}">
    window.location.href = document.currentScript.dataset.redir;
</script>
  • Related