I was just wondering if this code is enough to prevent XSS vulnerability in my web app?

 * Escape HTML string to prevent XSS.
export const escapeHtml = (string: string): string => {
    if (isString(string)) {
        const entityMap = {
            "&": "&",
            "<": "&lt;",
            ">": "&gt;",
            '"': "&quot;"
        return string.slice(0, string.length).replace(/[&<>"]/g, (s: string): string => entityMap[s]);
    return string;

 * Loop over Object to escape each of its value to prevent XSS.
export const escapeHtmlQueryObject = (obj: { [string]: string }): { [string]: string } => {
    let result = obj;
    if (obj && isObject(obj)) {
        result = Object.keys(obj).reduce((res: { [string]: string }, key: string): {
            [string]: string
        } => {
            res[key] = escapeHtml(obj[key]);
            return res;
        }, {});
    } else if (process.env.NODE_ENV !== "production" && process.env.NODE_ENV !== "test") {
        console.error(`FilterXSSQueryObject can't process ${obj.toString()}`);
    return result;
  • 3
    This is not a site for code review. If you want to know if your principal approach to the problem is the correct one ask exactly this instead of dumping code. Also, these are just functions definitions. Just having these defined does not prevent any XSS, but you also have to use these functions on all the relevant places. – Steffen Ullrich Aug 1 at 20:05

Since this is security.stackexchange and not stackoverflow, I can answer simply:

Don't write your own function for this requirement.

There are reliable libraries in every web language to do this. They have been hammered on by security experts and refined. Writing your own might be a good exercise for your own edification but don't use your own in production. Use an existing, vetted library.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.