TIL when to sanitize user input in a web application

1 minute read Published:

When a webapp takes user input (like a blog post or comment) and later renders that input into a HTML-Page, the webapp has to ensure that no malicious <script> tags or anything else is delivered to the viewer.

How to do that is actually pretty easy… Just replace " ' < and > with their HTML-Entity-Counterparts. But when do we have to do it??

Because we want the input’s author to see the exact same thing she entered into the text field, the webapp should not sanitize the text before it gets saved into the database, but rather before it gets delivered to the viewing client.

Some pseudocode:

function incoming( text ) {
  saveToDb( text );
}

function outgoing() {
  text = getFromDb();
  sendToClient( sanitize(text) );
}