Cross-site scripts (XSS) attack is where the attacker execute malicious scripts in a web browser of the victim by including malicious code in a legitimate web page or web application. An application is vulnerable to XSS if the application not sanitize user input and output.
So, basically, don’t trust user input!

In Laravel, we can avoid XSS Attack by using Middleware.
We can start by using existing AntiXSS package
composer require voku/anti-xss
After that,
Create a Middleware let’s say PurifyIncomingRequest.php
class PurifyIncomingRequest extends TransformsRequest {
...
}Add transform function
protected function transform($key, $value)
{
return (new AntiXSS())->xss_clean(trim($value))
}
Whats it do? Every input from client is checked by AntiXSS function. If there is any xss input, it will be sanitize
For example
$harmless_string = (new AntiXSS())->xss_clean("<a href=' javascript:alert(1)'>CLICK</a>");The output is just<a > Click</a> 🤘
So, the final code would be like below
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TransformsRequest;
class PurifyIncomingRequest extends TransformsRequest
{
protected $except = [
'password',
'password_confirmation',
];
protected function transform($key, $value)
{
if (in_array($key, $this->except, true)) {
return $value;
}
return $this->stripXSS($value);
}
private function stripXSS($value)
{
return is_string($value) ? strip_tags(antixss()->xss_clean(trim($value))) : $value;
}
}
Above code, i added some exclusion for password input. I want to avoid password input to be replace with other characters.
You can try on your own based on your implementation.
By the way… This is important…
Done rely on your code. You need to configure your web server configuration to add X-XSS-Protection in every http header. It will help you to defend against Cross-Site Scripting attacks. XSS Filter is only enabled by default in modern web browser such as, Chrome, IE, and Safari. This header stops pages from loading when they detect reflected XSS attacks.
Apache HTTP Server
Add the following entry in httpd.conf of your Apache webserver and restart the apache to verify
Header set X-XSS-Protection "1; mode=block"
Nginx
Add the following in nginx.conf under http block and restart your nginx
add_header X-XSS-Protection "1; mode=block";
That’s it. A simple validation in Laravel. Hope its help 😁
Thanks for your time.