You don't need to find a compromise. This is one of the cases where security and usability go hand in hand.
In an HTML context, you don't want to escape special characters, but encode them.
An example for escaping: " -> \"
An example for encoding: " -> "
The good thing with encoding in an HTML context is that it doesn't impact usability.
Say your user input is 3<5
. What you will put into the HTML response is 3<5
. What the user will see in their browser is 3<5
.
So there will be no impact on usability by fully encoding user-supplied data on output. It will actually improve usability. As this is a developer forum, what if users want to write A common XSS example is <img src=x onerror=alert(1)>
? If you don't encode, then this will be treated as HTML code, not as the string it is meant as.
If you actually need a subset of HTML because users want to format their comments (links, images, color, bold, etc), then you would want to use a HTML filter to ensure that the it's a safe HTML subset.
Stackexchange is a good example for this. In this answer, it would have been bad if <
wasn't encoded, because parts of the answer would not be properly formatted. But I can still format the answer using markdown.