Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sanitize user input string in nodejs, before injecting it in a template engine or say simple JS template string?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading