Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

300
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!