Secure Your Front-End: Preventing XSS and CSRF Attacks
Jul 29, 2025 am 03:59 AMTo defend against XSS and CSRF, sanitize user input using libraries like DOMPurify, avoid dangerous JavaScript methods such as innerHTML and eval(), implement a strict Content Security Policy, encode output when inserting user data, use anti-CSRF tokens tied to user sessions, set SameSite attributes on cookies (Lax or Strict), validate origin and referer headers cautiously, employ the double submit cookie pattern, and leverage built-in protections in frameworks like React and Angular while avoiding unsafe features; always treat user data as untrusted and apply layered security measures including secure HTTP headers to protect front-end applications effectively.
Front-end security is often overlooked, but it's just as critical as back-end protection. Two of the most common and dangerous client-side threats are Cross-Site Scripting (XSS) and Cross-Site Request Forgery (CSRF). While these attacks target different vulnerabilities, both can lead to data theft, account takeover, and loss of user trust. Here’s how to effectively defend your front-end applications.

1. Preventing Cross-Site Scripting (XSS)
XSS occurs when an attacker injects malicious scripts into web pages viewed by other users. These scripts run in the victim’s browser, potentially stealing cookies, session tokens, or redirecting to phishing sites.
Key Prevention Strategies:
-
Sanitize User Input
Never trust data from users. Always sanitize and validate input on both front-end and back-end. Use libraries like DOMPurify to clean HTML content before rendering:import DOMPurify from 'dompurify'; const clean = DOMPurify.sanitize(dirtyHTML);
Avoid Dangerous JavaScript Methods
Methods likeinnerHTML
,document.write()
, andeval()
can execute injected scripts. Prefer safer alternatives:- Use
textContent
instead ofinnerHTML
when inserting plain text. - Avoid
eval()
andnew Function()
with user-provided strings.
- Use
Use Content Security Policy (CSP)
CSP is a powerful HTTP header that restricts which scripts can run on your page. For example:Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted-cdn.com;
This blocks inline scripts and only allows scripts from your domain and approved CDNs.
Encode Output
When dynamically inserting user data into HTML, ensure it’s properly encoded. Most modern frameworks (React, Angular, Vue) do this automatically, but be cautious withdangerouslySetInnerHTML
in React.
2. Blocking Cross-Site Request Forgery (CSRF)
CSRF tricks a user’s browser into making unintended requests to a site where they’re authenticated—like changing a password or making a payment—without their knowledge.
Effective CSRF Protections:
Use Anti-CSRF Tokens
Generate a unique, unpredictable token for each user session and include it in forms or API requests. The server must validate this token before processing the request.<input type="hidden" name="csrf_token" value="unique-random-value">
This token should be tied to the user’s session and regenerated per session.
Leverage SameSite Cookie Attribute
Set cookies withSameSite=Strict
orSameSite=Lax
to prevent browsers from sending them in cross-site requests:Set-Cookie: sessionId=abc123; Path=/; Secure; HttpOnly; SameSite=Lax
-
Lax
: Allows cookies in safe top-level navigations (e.g., link clicks). -
Strict
: Blocks cookies in all cross-site contexts (more secure but can break some flows).
-
Validate Origin and Referer Headers (with caution)
On sensitive actions, check that the request originated from your domain. However, don’t rely solely on these headers—they can be spoofed or missing in some cases.Use Double Submit Cookie Pattern
Store a random token in a cookie and also send it in the request body or header. Since an attacker can’t read your cookie (due to same-origin policy), they can’t replicate the token in the request.
Bonus: Framework-Specific Tips
-
React / Angular / Vue: These frameworks offer built-in XSS protections (e.g., automatic escaping), but remain cautious with bypass features like
dangerouslySetInnerHTML
orv-html
. -
SPA API Architecture: Ensure your API checks CSRF tokens or uses
SameSite
cookies. Consider using JWT with proper storage (avoid localStorage for sensitive tokens).
Securing your front-end isn’t about one magic fix—it’s layers. Combine input sanitization, secure headers, anti-forgery tokens, and smart cookie policies. Most attacks succeed due to small oversights, so stay consistent. Basically, treat every piece of user data as untrusted, and let the browser help you with modern security headers.
The above is the detailed content of Secure Your Front-End: Preventing XSS and CSRF Attacks. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

According to news from this website on July 5, the Japan Aerospace Exploration Agency (JAXA) issued an announcement today, confirming that the cyber attack suffered last year led to the leakage of information, and apologized to relevant units for this. JAXA stated that the information leaked this time includes not only the internal information of the agency, but also information related to joint operations with external organizations and personal information. JAXA believes that "this matter may damage the relationship of trust", but will not provide it due to the relationship with the other party. details. In this regard, JAXA has apologized to the individuals and related parties who leaked the information and notified them one by one. As of now, JAXA has not received any reports of any significant impact on the business activities of relevant personnel, but they deeply apologize for any inconvenience caused and apologize again. This site noticed that JA

With the rapid development and popularization of information technology, network hacker attacks have become a global problem. Cyber ??hacker attacks not only bring huge economic losses to businesses and individuals, but also have a huge impact on people's mental health. Therefore, studying the psychology of network hacker attacks will not only help understand the behavioral motivations and psychological states of hackers, but also help people face the problem of network hacker attacks more rationally. First of all, there are two main psychological motivations for hacker attacks: one is the love for technology and the desire to prove it through hacker attacks.

The current network attack model is multi-faceted and multi-method, making it difficult to guard against. Generally speaking, they are divided into four categories: denial of service attacks, exploitation attacks, information collection attacks, and fake news attacks.

The types of network attacks are: 1. Active attacks, which will lead to the tampering of certain data flows and the generation of false data flows; such attacks can be divided into tampering, forging message data and terminal (denial of service). 2. Passive attacks usually include eavesdropping, traffic analysis, cracking weakly encrypted data streams and other attack methods.

As the complexity of front-end applications continues to increase, web application security issues are becoming more and more important. The same-origin policy is an important security measure to avoid security issues such as cross-site scripting attacks. Nginx is a powerful web server software. This article will introduce how to use Nginx to configure the same-origin policy to protect front-end security. 1. Same-origin policy The same-origin policy is a security principle in web development that is used to restrict how documents or scripts under one domain name interact with resources under another domain name. Same origin refers to the protocol, domain name and terminal

A powerful tool to defend against network attacks: Use of Linux commands Network attacks have become a major challenge in today's Internet era. In order to protect the network security of individuals, organizations and enterprises, we need to master some powerful tools to defend against network attacks. In Linux systems, many powerful commands can help us improve network security. This article will introduce several commonly used Linux commands and provide corresponding code examples to help readers better understand and use these commands. View network connections netstat-annetstat command

The threat of cyberattacks has increased dramatically recently, and traditional measures now seem insufficiently effective. Because of this, deep learning in cybersecurity is rapidly making progress and may hold the key to solving all cybersecurity problems. With the advent of technology, threats to data security have increased, requiring the use of cybersecurity tools to protect an organization's operations. However, businesses are struggling due to their reliance on most cybersecurity tools. Enterprises rely on signatures or evidence of compromise to detect the threat detection capabilities of the technology they use to protect their business. Because they are only useful for identifying recognized risks, these techniques are useless against unknown attacks. This is where deep learning in cybersecurity can change the course of events. Deep learning is a branch of machine learning,

With the popularity of Docker container technology, more and more enterprises are adopting containerization technology to deploy their own applications. Compared with traditional virtualization technology, Docker containers use more lightweight virtualization technology and have the advantages of rapid deployment, easy management, and high scalability. However, when using Docker container technology, security issues have gradually surfaced. The isolation of networks between containers is not perfect, and container security issues deserve attention. This article will introduce how to use Nginx to run a Docker container environment
