0

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?

1

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.