To prevent XSS, web applications should follow the principle of never trusting user input and always validating and sanitizing it before rendering it on the web page. Validation means checking if the input conforms to the expected format, length, and type, and rejecting any input that does not meet the criteria. Sanitization means removing or escaping any characters that can be interpreted as code, such as <, >, ", ', and /. Web applications should also use secure coding practices, such as using parameterized queries, prepared statements, or stored procedures for database operations, and using HTML encoding, URL encoding, or content security policy for output encoding. Additionally, web applications should use HTTP-only and secure flags for cookies, and implement anti-XSS libraries or frameworks.