I want to prevent cross-site scripting attacks in web applications I make. If someone could provide me with some suggestions and advice, it would be really helpful.

AndreRet commented: Google is your friend here... +15
robertoben41 commented: To prevent cross-site scripting (XSS) attacks, sanitize user inputs, validate and encode data before displaying, use Content Security Policy (CSP), an +0

I briefly answered your question here by saying:

To prevent cross-site scripting attacks, you similarly want to make sure that all text derived from user-generated input is HTML escaped. If using PHP, you can use the htmlspecialchars() function.

It really is that simple, if you're using PHP. I do see you tagged this code Javascript, so here's a quick JS function I found on this page of SO that you can use:

function escape(s) {
    let lookup = {
        '&': "&",
        '"': """,
        '\'': "'",
        '<': "&lt;",
        '>': "&gt;"
    };
    return s.replace( /[&"'<>]/g, c => lookup[c] );
}
console.log(escape("<b>This is 'some' text.</b>"));

As you can see, all it takes to escape HTML code is to replace &, ", ', < and >. Ampersand, double quote, single quote, less than, and greater than are kinda like reserved characters in HTML. Once you escape those, no one can inject user-generated content to execute HTML or JS on your page that you don't want it to, which is what an XSS attack is.

In whatever code language is running on the server, use a well known database library that is well documented and features XSS aka sql injection prevention.

Minimize the use of inline JavaScript within your HTML code. Instead, use external JavaScript files and scripts to separate content from functionality.Ensure that sensitive cookies have the HttpOnly and Secure flags set.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.