Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Disable Ctrl+V (Paste) in JavaScript?
Next article icon

How to Prevent XSS Attacks in JavaScript?

Last Updated : 14 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cross-site scripting (XSS) is a security vulnerability that enables attackers to inject malicious scripts into web pages viewed by users, potentially leading to serious consequences such as data theft and unauthorized actions.

Given that JavaScript is a fundamental technology in web development, it is crucial to understand how to prevent XSS attacks in JavaScript.

This article explores three effective approaches to safeguarding against XSS vulnerabilities, detailing each method with descriptions, syntax, and executable code examples. By implementing these strategies, developers can enhance the security of their applications and protect users from potential threats.

Types of XSS Attacks

  • Stored XSS: The Malicious scripts are injected into the website's database and served to the users when they request the affected page.
  • Reflected XSS: The Malicious scripts are reflected off a web application to the user via a URL or form submission.
  • DOM-Based XSS: The Malicious scripts manipulate the Document Object Model (DOM) in the user's browser to execute without reaching the server.

Below are the ways to prevent XSS Attacks:

Table of Content

  • Input Validation and Sanitization
  • Content Security Policy (CSP)
  • Use HttpOnly and Secure Cookies
  • Preventing Specific Types of XSS Attacks
  • Escaping User Input

Input Validation and Sanitization

Ensure that all user inputs are validated and sanitized before processing or displaying them. This helps to remove any potentially harmful code.

Example: Below is the example of Input Validation and Sanitization to prevent XSS Attacks in JavaScript

function sanitizeInput(input) {     const element = document.createElement('div');     element.innerText = input;     return element.innerHTML; } const userInput = "<script>alert('XSS');</script>"; const sanitizedInput = sanitizeInput(userInput); console.log(sanitizedInput); 

Output:

&lt;script&gt;alert('XSS');&lt;/script&gt;

Content Security Policy (CSP)

Implementing a Content Security Policy (CSP) helps to prevent XSS by specifying which sources of the content are allowed to be loaded on the webpage.

Example: Below is the example of Content Security Policy (CSP) to prevent XSS Attacks in JavaScript

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.com;">

This CSP allows scripts to be loaded only from the same origin and a trusted CDN.

Use HttpOnly and Secure Cookies

The Setting the HttpOnly and Secure flags on cookies can prevent client-side scripts from the accessing cookies and ensure that cookies are only sent over secure HTTPS connections.

Example: Below is the example demonstrating the use of HTTP and Cookies to prevent XSS Attacks in JavaScript.

document.cookie = "sessionId=abc123; HttpOnly; Secure";

Preventing Specific Types of XSS Attacks

Stored XSS Prevention

Ensure that all data stored in the database is sanitized before being the saved and before being rendered on the webpage.

// Server-side pseudo-code example function saveUserComment(comment) {     const sanitizedComment = sanitizeInput(comment);     database.save(sanitizedComment); } function displayUserComment(comment) {     const sanitizedComment = sanitizeInput(comment);     document.getElementById('commentSection').innerHTML += `<p>${sanitizedComment}</p>`; }

Reflected XSS Prevention

The Sanitize any input that is reflected back to the user immediately.

// Server-side pseudo-code example app.get('/search', (req, res) => {     const query = sanitizeInput(req.query.q);     res.send(`Search results for: ${query}`); });

DOM-Based XSS Prevention

Ensure that dynamic content manipulated by the JavaScript is properly sanitized.

function updatePageContent(content) {     const sanitizedContent = sanitizeInput(content);     document.getElementById('content').innerHTML = sanitizedContent; }

Escaping User Input

The Escaping user input is a fundamental technique to the prevent XSS attacks. This approach involves converting special characters in the user input into their HTML-encoded equivalents. By doing so any potentially harmful scripts are rendered as the plain text rather than executable code.

Example: Below is the example demonstrating escaping user Input to prevent XSS Attacks in JavaScript

<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport" content="width=device-width, initial-scale=1.0">     <title>Escaping User Input Example</title> </head>  <body>     <h1>Escaping User Input Example</h1>     <div id="output"></div>     <script>         function escapeHtml(unsafe) {             return unsafe                 .replace(/&/g, "&amp;")                 .replace(/</g, "&lt;")                 .replace(/>/g, "&gt;")                 .replace(/"/g, "&quot;")                 .replace(/'/g, "&#039;");         }          // Example user input         let userInput = '<script>alert("XSS Attack!");</script>';     document.getElementById('output').innerHTML = escapeHtml(userInput);     </script> </body>  </html>

Output:

The content will be displayed as:

<script>alert("XSS Attack!");</script>

Conclusion

The Preventing XSS attacks is essential for the maintaining web application security. By escaping and sanitizing user input and using the Content Security Policy (CSP) developers can effectively mitigate the risk of the XSS vulnerabilities. Implementing these practices will help create a safer browsing the experience for the users and protect web applications from the malicious attacks.


Next Article
How to Disable Ctrl+V (Paste) in JavaScript?

V

vinodhajqv5
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • JavaScript-Questions

Similar Reads

  • How to Print a String in JavaScript ?
    In JavaScript, printing a string means displaying the contents of a string variable or literal to the console, webpage, or any other output medium. Strings are a fundamental data type in JavaScript, representing sequences of characters enclosed within single ('') or double ("") quotes. Table of Cont
    2 min read
  • How to use the alert() method in JavaScript ?
    In this article, we will learn how to use the alert() method in JavaScript. The alert() method is used to show an alert box on the browser window with some message or warning. We can use it as a message or as a warning for the user. Approach: To show an alert on the browser window, we make a button.
    2 min read
  • How to Set & Retrieve Cookies using JavaScript ?
    In JavaScript, setting and retrieving the cookies is an important task for assessing small pieces of data on a user's browser. This cookie can be useful for storing user preferences, session information, and many more tasks. Table of Content Using document.cookieUsing js-cookie libraryUsing document
    2 min read
  • How to prevent the Common Vulnerabilities in JavaScript ?
    In this article, we will see the Preventing Common Vulnerabilities in JavaScript. Before we proceed, we will first understand the list of most common Vulnerability attacks, & then will understand the various approaches to resolve those Vulnerability attacks. Finally, we will understand the conce
    4 min read
  • How to Disable Ctrl+V (Paste) in JavaScript?
    What is Ctrl + V ?The ctrl+V is a keyboard shortcut used to paste anything from anywhere. It can be disabled for a particular task or page. Let's see how to disable cut, copy, paste, and right-click. To disable the ctrl+V (paste) keyboard shortcut in JavaScript, you would typically capture the keydo
    2 min read
  • How to prevent overriding using fake namespace in JavaScript ?
    Overriding is basically when you define multiple functions or variables that have the same name, the last one defined will override all the previously defined ones and every time when you invoke a function, the last defined one will get executed. Overriding usually happens when you have multiple jav
    2 min read
  • How to Detect Keypress using JavaScript ?
    In this article, keyboard detection is performed using HTML and CSS. HTML stands for "Hypertext Markup Language". HTML language helps the developer to create and design web page elements like links, sections, paragraphs, headings, and blockquotes for web applications. CSS stands for "Cascading Style
    2 min read
  • How to Create an Alert in JavaScript ?
    The alert() method in JavaScript displays an alert box with a message and an OK button. It's used when you want information to come through to the user, providing immediate notifications or prompts for user interaction during program execution. Note: Alert boxes interrupt user interaction, shifting
    1 min read
  • How to modify a string in JavaScript ?
    JavaScript strings are used for storing and manipulating text. It can contain zero or more characters within quotes and its indexing starts with 0. Strings are defined as an array of characters. In Javascript, we can also convert strings to a Character array.  Representing a String:  1. Using double
    3 min read
  • How to Validate XML against XSD in JavaScript ?
    XML (Extensible Markup Language) is a widely used format for storing and exchanging structured data. XSD (XML Schema Definition) is a schema language used to define the structure, content, and data types of XML documents. Validating XML against XSD ensures that the XML document conforms to the speci
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences