Skip to main content

Displaying user-inputted content on webpages

XSS (Cross-Site Scripting) generally results from bad practices regarding user input. For example, suppose there is a simple HTML text box for users to comment on an artwork, and a user writes:

<script>
alert('Execute order 66');
</script>

If this comment is not properly sanitised when being displayed on the page, users visiting that artwork will suddenly have a popup on their screen instructing them to execute order sixty-six. Irrespective of whether your user is a clone trooper willing to obey that instruction, this is not something you want to happen, as that script could be an awful lot more damaging.

Sanitising content against XSS attacks

While you can sanitise content at the time of user submission in client side code, it's not really useful to do so. The user can easily override your scripts and send anything to the server - you must validate it when displaying it on any webpage, no matter what checks you performed clientside on submission.

Having the above script, exactly as it is, sitting in your database as a user comment is not a problem; however, you must ensure that whenever you display any content that has been submitted by a user, that it is first sanitised to remove any potential script or other malicious elements.

Many text editing libraries (e.g. TinyMCE, QuillJS and so forth) will automatically sanitize and validate input passed to them for display on a page, making this step easier. If you are displaying content in e.g. a normal HTML element, you need to do this yourself, ideally in some standardised manner. The DOMPurify Library is an excellent tool for this, though others exist.