How do you prevent XSS?
Escape output (React does this by default), strip HTML from input with xss-clean or dompurify, set a Content Security Policy with helmet, use httpOnly cookies, and sanitize rich text on render.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Validation and Sanitization Interview Questions and Answers
Validation rejects bad input (is this valid?). Sanitization cleans input (is this safe?). Use both. Validate the shape with Zod, then sanitize the values with transforms and middlewares.
Use express-mongo-sanitize (strips $ and .), validate with Zod (enforces types), use Mongoose (casts based on schema), cast inputs explicitly with String(), avoid $where, and whitelist filter fields. Layer defenses.
In a middleware, applied per route. Not in controllers (duplication) and not in models (mixing concerns). The middleware runs before the handler so the handler only sees valid input.
Still have questions?
Browse all our FAQs or reach out to our support team
