Where to escape html?

Viewed 61

I'm writing some code using angularjs, node.js, and mongodb which allows users to add comments which are stored in mongodb by a server running on node.js.

My strategy is to replace < and > with gt and lt. Where should I do this? If I do it in the client, someone could bypass it by posting to my server using something like postman, although google captcha may help at least a little there.

If I do the escaping at the server, is it too late? I would like to intercept it in the server route and do the manipulation before it is stored in mongo.

Or, in the context of just storing comments, do I even need to do something like this at all?

1 Answers

You do not need to do the escaping yourself. MongoDB can handle the special characters just fine. Since it does not use any SQL so no worries for any SQL injections. You can just store exactly what the user types in the comment into the DB directly.

However, you might consider validating those texts to avoid some people that try to inject JavaScript code in the comment, which will lead to a XSS attack.

As for what you want to do with the data from the client-side, you should, if possible, always process that data in the backend (server-side) because once your app or web are out there publicly, it is exposed to hacking tools.

Related