How to escape HTML in node.js EJS view?

There are some tags in EJS which can dynamically change the data inside the HTML page. we can also perform different type of operations, use conditionals, and these are the tags used in EJS to manipulate and modify HTML page.

  • <% ‘Scriptlet’ tag, for control-flow, no output
  • <%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
  • <%= Outputs the value into the template (HTML escaped)
  • <%- Outputs the unescaped value into the template
  • <%# Comment tag, no execution, no output
  • <%% Outputs a literal ‘<%’
  • %> Plain ending tag
  • -%> Trim-mode (‘newline slurp’) tag, trims following newline
  • _%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it

How to Escape HTML in NodeJS EJS View ?

When working with web applications in Node.js using the EJS templating engine, it’s important to ensure that user-generated content containing HTML is rendered safely. Otherwise, it can lead to security vulnerabilities such as cross-site scripting (XSS) attacks.

Prerequisites:

Similar Reads

Why do we use EJS?

EJS (Embedded JavaScript) is a popular templating engine for Node.js applications. It allows you to embed JavaScript code directly into HTML templates, making it easier to generate dynamic content. However, when rendering user-generated data, precautions must be taken to prevent XSS attacks....

How to escape HTML in node.js EJS view?

There are some tags in EJS which can dynamically change the data inside the HTML page. we can also perform different type of operations, use conditionals, and these are the tags used in EJS to manipulate and modify HTML page....

Escape HTML in node.js EJS view

Step 1: Create a folder or go to the existing folder...

Approach 1: Using the tag <%= %>

By default, EJS uses <%= %> tags to output unescaped values....

Approach 2: Using the tag <%- %>

This tag can be use to escape HTML and you can write javascript inside it....