Sanitizing Output

Learn how to sanitize your output in Node.js.

Outputting to the browser

Take precautions when saving data you take in. Sanitize or escape any user-generated data that is output back to the browser.

You can modify and escape your data before saving to the database, or in between by retrieving and outputting it to the browser. This depends on how your data is edited and used. For example, if the user is editing the data later, it makes more sense to save as-is and sanitize upon output.

What security benefits come from escaping user-generated data that you output? Suppose a user submits the following JavaScript snippet to your application, which then saves it for outputting later:

<script>alert('I am not sanitized!');</script>

If you don’t sanitize this code before echoing it to the browser, the malicious JavaScript will run as if you wrote it yourself. In this case, it’s a harmless alert(), but a hacker won’t be nearly as kind.

An image’s EXIF data is another popular exploit. If a user uploads an image and your application displays the XIFF data, it needs to be sanitized. Always sanitize displayed data that came into your app from the outside.

If you’re using a templating library or a framework that handles templating, escaping may happen automatically. Make sure to check the documentation for your library/framework of choice to determine how this works.

You may choose to handle this yourself. The html-escape library provides a function that will be your best friend when displaying data. Simply call the escape() method on your data to replace it with properly escaped HTML:

Get hands-on with 1400+ tech skills courses.