Security for your Frontend application

Next.js is a web framework based on React.js. React offers extensive functionality and protection against cross-site scripting (XSS) attacks. However, it's crucial to remain vigilant when developing web applications without any framework or using vanilla.js.

While modern frameworks implement measures to mitigate XSS attacks, comprehending how these attacks occur remains essential. This understanding keeps developers alert to potential vulnerabilities and ensures robust security practices.

Cross-site scripting (XSS)

Cross-site scripting or XSS is one of the most common types of attack that occurs on the client side. In a typical XSS attack, the attacker can inject and execute malicious scripts into the user’s browser. Now let us understand the types of attack

  1. Reflected XSS

This type of attack occurs when the input provided by the user is directly reflected back to the to the browser, this attack is mostly initiated from the URL’s query params.

The attacker will craft a phishing link that will have the malicious scripts in the URL’s query param. This query param will be sent to the backend server which without validating it return back to client in a json response. The response will be rendered on the browser.

In this kind of attack the attacker uses a specially crafted URL that will be shared with the user something like this

https://example.com/search?q=<script>alert('XSS');</script>

the search query param will be passed to the user. When the user the URL and returns it to user returns it without escaping.

<div>
  <h1>Search Results for: <script>alert('XSS');</script></h1>
  <ul>
    <li>Result 1</li>
    <li>Result 2</li>
    <!-- ... -->
  </ul>
</div>
  1. Stored XSS

In the realm of stored XSS the attacker is able to store the malicious script in the database making it affect whole range of users that using the site. This attack is initiated by storing the malicious script in the database like

app.post('/update-profile', (req, res) =>{
	const userProfileDesc = req.body.description;
	
	//storing the user provided input without proper validation
	const savedProfile = saveProfileDescriptionDatabase(userProfileDesc);
	
	res.send(savedProfile)
})

function saveProfileDescription(userProfileDesc){

	const savedDesc = db.save({description: userProfileDesc})
	
	return savedDesc;
}

Now lets say the attacker provides following the malicious sprint in the place of user description

//malicious script is being provided here. 
<script>

window.location.href = 'https://attacker.com';
</script>