{ Soham Kamani }

AboutBlog GithubTwitter

Web security essentials - XSS 🔑

XSS(Cross site scripting) attacks are one one of the easiest attacks to perform, and are often the starting point for many attackers looking to compromise your website. Fortunately, they are also one of the easiest to avoid.

The best way to explain what XSS is, is to dive right into an example. This is an HTML element :

<div id="status">
  I am feeling alright

Let’s assume this div is used to show your status on a popular social media site. It will be seen by many of your friends on their news feed and be seen as : “I am feeling alright”. As a user, you can update your status to whatever you want, and it will appear inside this div element.

If you were to be a malicious user, you could change your status from “I am feeling alright” to ”<script>alert(‘I am feeling great!‘)</script>”, but the thing is, your friends would not see your status as ”<script>alert(‘I am feeling great!‘)</script>”, but instead, they would get an alert message which would look something like this :


This is because the text you just put in is rendered to HTML by default, which will make the content inside the div look like this :

<div id="status">
    alert('I am feeling great!')

Everything inside the script tag is considered as javascript code and executed. Thus, everyone across the site has this script executed, and the attacker has now compromised the site.

Although this was a rather innocent example, there are a lot of more sinister things that can be done this way, like submitting a form on someone else’s behalf.

Preventing XSS

Make sure all information being rendered on the browser is HTML encoded first. This means converting some special characters to their HTML encoded equivalents first.

Here’s a list of all special characters in HTML and their character code in HTML.

Try it out for yourself! Enter some text with some sensitive HTML characters, and see the encoded output on the right :

Many frameworks and tools like jQuery, angular, and react have this built in so you don’t normally have to worry. But this is still something you should keep an eye out for.

If you want to learn more about security on the web, be sure to read my other posts on web security essentials :

SQL Injection
CORS (Cross origin resource sharing)
Password storage
Sessions and cookies
CSRF (Cross site request forgery)
Human Error and UI/UX design

Like what I write? Join my mailing list, and I'll let you know whenever I write another post


Soham Kamani

Written by Soham Kamani, an author,and a full-stack developer who has extensive experience in the JavaScript ecosystem, and building large scale applications in Go. He is an open source enthusiast and an avid blogger. You should follow him on Twitter