Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Apply modern web development best practices for security, compatibility, code quality, and coding standards. Covers KISS/DRY/YAGNI principles, TypeScript/JavaScript standards, React patterns, write-time quality enforcement, and comprehensive code review checklists.
| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 175% | 0% |
| case-06 | ✗→✓ | ▲ Improved | 259% | 0% |
| case-07 | ✗→✓ | ▲ Improved | 183% | 0% |
| case-09 | ✗→✓ | ▲ Improved | 217% | 0% |
| case-04 | ✓→✓ | = Same ✓ | 207% | 0% |
Modern web development standards based on Lighthouse best practices audits and production-proven coding standards. Covers security, browser compatibility, code quality patterns, and write-time enforcement.
typescript// ✅ GOOD: Descriptive names const marketSearchQuery = 'election' const isUserAuthenticated = true const totalRevenue = 1000 // ❌ BAD: Unclear names const q = 'election' const flag = true const x = 1000
typescript// ✅ GOOD: Verb-noun pattern async function fetchMarketData(marketId: string) { } function calculateSimilarity(a: number[], b: number[]) { } function isValidEmail(email: string): boolean { } // ❌ BAD: Unclear or noun-only async function market(id: string) { } function similarity(a, b) { } function email(e) { }
typescript// ✅ ALWAYS use spread operator const updatedUser = { ...user, name: 'New Name' } const updatedArray = [...items, newItem] // ❌ NEVER mutate directly user.name = 'New Name' // BAD items.push(newItem) // BAD
typescript// ✅ GOOD: Comprehensive error handling async function fetchData(url: string) { try { const response = await fetch(url) if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`) } return await response.json() } catch (error) { console.error('Fetch failed:', error) throw new Error('Failed to fetch data') } } // ❌ BAD: No error handling async function fetchData(url) { const response = await fetch(url) return response.json() }
typescript// ✅ GOOD: Parallel execution when possible const [users, markets, stats] = await Promise.all([ fetchUsers(), fetchMarkets(), fetchStats() ]) // ❌ BAD: Sequential when unnecessary const users = await fetchUsers() const markets = await fetchMarkets() const stats = await fetchStats()
typescript// ✅ GOOD: Proper types interface Market { id: string name: string status: 'active' | 'resolved' | 'closed' created_at: Date } function getMarket(id: string): Promise<Market> { // Implementation } // ❌ BAD: Using 'any' function getMarket(id: any): Promise<any> { // Implementation }
typescript// ✅ GOOD: Functional component with types interface ButtonProps { children: React.ReactNode onClick: () => void disabled?: boolean variant?: 'primary' | 'secondary' } export function Button({ children, onClick, disabled = false, variant = 'primary' }: ButtonProps) { return ( <button onClick={onClick} disabled={disabled} className={`btn btn-${variant}`} > {children} </button> ) } // ❌ BAD: No types, unclear structure export function Button(props) { return <button onClick={props.onClick}>{props.children}</button> }
typescript// ✅ GOOD: Reusable custom hook export function useDebounce<T>(value: T, delay: number): T { const [debouncedValue, setDebouncedValue] = useState<T>(value) useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value) }, delay) return () => { clearTimeout(handler) } }, [value, delay]) return debouncedValue } // Usage const debouncedSearch = useDebounce(searchQuery, 300)
Before submitting code for review:
markdown### Functionality - [ ] Code works as intended - [ ] Edge cases handled - [ ] Error paths tested - [ ] No hardcoded secrets or values ### Code Quality - [ ] Follows naming conventions - [ ] No code duplication (DRY) - [ ] Functions are focused (single responsibility) - [ ] No unnecessary complexity (KISS) - [ ] No speculative features (YAGNI) ### TypeScript/JavaScript - [ ] Proper types (no `any`) - [ ] Null checks where needed - [ ] Async/await used correctly - [ ] No mutation of props/state ### React - [ ] Proper hook dependencies - [ ] No memory leaks (cleanup) - [ ] Keys provided for lists - [ ] Accessibility attributes ### Testing - [ ] Unit tests added/updated - [ ] Integration tests if needed - [ ] All tests passing - [ ] No test coverage gaps ### Documentation - [ ] Complex logic commented - [ ] API changes documented - [ ] README updated if needed
Configure your editor to format on save:
json// VS Code settings.json { "editor.formatOnSave": true, "editor.defaultFormatter": "esbenp.prettier-vscode", "[typescript]": { "editor.defaultFormatter": "vscode.typescript-language-features" } }
json// package.json { "husky": { "hooks": { "pre-commit": "lint-staged" } }, "lint-staged": { "*.{ts,tsx}": ["eslint --fix", "prettier --write"], "*.{js,jsx}": ["eslint --fix", "prettier --write"] } }
For automatic quality enforcement during Claude Code sessions:
json// .claude/settings.json { "hooks": { "PostToolUse": [{ "matcher": "Write|Edit", "hooks": [{ "type": "command", "command": "npm run lint:fix" }] }] } }
Enforce HTTPS:
html<!-- ❌ Mixed content --> <img src="http://example.com/image.jpg"> <script src="http://cdn.example.com/script.js"></script> <!-- ✅ HTTPS only --> <img src="https://example.com/image.jpg"> <script src="https://cdn.example.com/script.js"></script> <!-- ✅ Protocol-relative (will use page's protocol) --> <img src="//example.com/image.jpg">
HSTS Header:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadhtml<!-- Basic CSP via meta tag --> <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' https://trusted-cdn.com; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com;"> <!-- Better: HTTP header -->
CSP Header (recommended):
Content-Security-Policy:
default-src 'self';
script-src 'self' 'nonce-abc123' https://trusted.com;
style-src 'self' 'nonce-abc123';
img-src 'self' data: https:;
connect-src 'self' https://api.example.com;
frame-ancestors 'self';
base-uri 'self';
form-action 'self';Using nonces for inline scripts:
html<script nonce="abc123"> // This inline script is allowed </script>
# Prevent clickjacking
X-Frame-Options: DENY
# Prevent MIME type sniffing
X-Content-Type-Options: nosniff
# Enable XSS filter (legacy browsers)
X-XSS-Protection: 1; mode=block
# Control referrer information
Referrer-Policy: strict-origin-when-cross-origin
# Permissions policy (formerly Feature-Policy)
Permissions-Policy: geolocation=(), microphone=(), camera=()bash# Check for vulnerabilities npm audit yarn audit # Auto-fix when possible npm audit fix # Check specific package npm ls lodash
Keep dependencies updated:
json// package.json { "scripts": { "audit": "npm audit --audit-level=moderate", "update": "npm update && npm audit fix" } }
Known vulnerable patterns to avoid:
javascript// ❌ Prototype pollution vulnerable patterns Object.assign(target, userInput); _.merge(target, userInput); // ✅ Safer alternatives const safeData = JSON.parse(JSON.stringify(userInput));
javascript// ❌ XSS vulnerable element.innerHTML = userInput; document.write(userInput); // ✅ Safe text content element.textContent = userInput; // ✅ If HTML needed, sanitize import DOMPurify from 'dompurify'; element.innerHTML = DOMPurify.sanitize(userInput);
javascript// ❌ Insecure cookie document.cookie = "session=abc123"; // ✅ Secure cookie (server-side) Set-Cookie: session=abc123; Secure; HttpOnly; SameSite=Strict; Path=/
html<!-- ❌ Missing or invalid doctype --> <HTML> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <!-- ✅ HTML5 doctype --> <!DOCTYPE html> <html lang="en">
html<!-- ❌ Missing or late charset --> <html> <head> <title>Page</title> <meta charset="UTF-8"> </head> <!-- ✅ Charset as first element in head --> <html> <head> <meta charset="UTF-8"> <title>Page</title> </head>
html<!-- ❌ Missing viewport --> <head> <title>Page</title> </head> <!-- ✅ Responsive viewport --> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Page</title> </head>
javascript// ❌ Browser detection (brittle) if (navigator.userAgent.includes('Chrome')) { // Chrome-specific code } // ✅ Feature detection if ('IntersectionObserver' in window) { // Use IntersectionObserver } else { // Fallback } // ✅ Using @supports in CSS @supports (display: grid) { .container { display: grid; } } @supports not (display: grid) { .container { display: flex; } }
html<!-- Load polyfills conditionally --> <script> if (!('fetch' in window)) { document.write('<script src="/polyfills/fetch.js"><\/script>'); } </script> <!-- Or use polyfill.io --> <script src="https://polyfill.io/v3/polyfill.min.js?features=fetch,IntersectionObserver"></script>
javascript// ❌ document.write (blocks parsing) document.write('<script src="..."></script>'); // ✅ Dynamic script loading const script = document.createElement('script'); script.src = '...'; document.head.appendChild(script); // ❌ Synchronous XHR (blocks main thread) const xhr = new XMLHttpRequest(); xhr.open('GET', url, false); // false = synchronous // ✅ Async fetch const response = await fetch(url); // ❌ Application Cache (deprecated) <html manifest="cache.manifest"> // ✅ Service Workers if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/sw.js'); }
javascript// ❌ Non-passive touch/wheel (may block scrolling) element.addEventListener('touchstart', handler); element.addEventListener('wheel', handler); // ✅ Passive listeners (allows smooth scrolling) element.addEventListener('touchstart', handler, { passive: true }); element.addEventListener('wheel', handler, { passive: true }); // ✅ If you need preventDefault, be explicit element.addEventListener('touchstart', handler, { passive: false });
javascript// ❌ Errors in production console.log('Debug info'); // Remove in production throw new Error('Unhandled'); // Catch all errors // ✅ Proper error handling try { riskyOperation(); } catch (error) { // Log to error tracking service errorTracker.captureException(error); // Show user-friendly message showErrorMessage('Something went wrong. Please try again.'); }
jsxclass ErrorBoundary extends React.Component { state = { hasError: false }; static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, info) { errorTracker.captureException(error, { extra: info }); } render() { if (this.state.hasError) { return <FallbackUI />; } return this.props.children; } } // Usage <ErrorBoundary> <App /> </ErrorBoundary>
javascript// Catch unhandled errors window.addEventListener('error', (event) => { errorTracker.captureException(event.error); }); // Catch unhandled promise rejections window.addEventListener('unhandledrejection', (event) => { errorTracker.captureException(event.reason); });
javascript// ❌ Source maps exposed in production // webpack.config.js module.exports = { devtool: 'source-map', // Exposes source code }; // ✅ Hidden source maps (uploaded to error tracker) module.exports = { devtool: 'hidden-source-map', }; // ✅ Or no source maps in production module.exports = { devtool: process.env.NODE_ENV === 'production' ? false : 'source-map', };
javascript// ❌ Blocking script <script src="heavy-library.js"></script> // ✅ Deferred script <script defer src="heavy-library.js"></script> // ❌ Blocking CSS import @import url('other-styles.css'); // ✅ Link tags (parallel loading) <link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="other-styles.css">
javascript// ❌ Handler on every element items.forEach(item => { item.addEventListener('click', handleClick); }); // ✅ Event delegation container.addEventListener('click', (e) => { if (e.target.matches('.item')) { handleClick(e); } });
javascript// ❌ Memory leak (never removed) const handler = () => { /* ... */ }; window.addEventListener('resize', handler); // ✅ Cleanup when done const handler = () => { /* ... */ }; window.addEventListener('resize', handler); // Later, when component unmounts: window.removeEventListener('resize', handler); // ✅ Using AbortController const controller = new AbortController(); window.addEventListener('resize', handler, { signal: controller.signal }); // Cleanup: controller.abort();
html<!-- ❌ Invalid HTML --> <div id="header"> <div id="header"> <!-- Duplicate ID --> <ul> <div>Item</div> <!-- Invalid child --> </ul> <a href="/"><button>Click</button></a> <!-- Invalid nesting --> <!-- ✅ Valid HTML --> <header id="site-header"> </header> <ul> <li>Item</li> </ul> <a href="/" class="button">Click</a>
html<!-- ❌ Non-semantic --> <div class="header"> <div class="nav"> <div class="nav-item">Home</div> </div> </div> <div class="main"> <div class="article"> <div class="title">Headline</div> </div> </div> <!-- ✅ Semantic HTML5 --> <header> <nav> <a href="/">Home</a> </nav> </header> <main> <article> <h1>Headline</h1> </article> </main>
html<!-- ❌ Distorted images --> <img src="photo.jpg" width="300" height="100"> <!-- If actual ratio is 4:3, this squishes the image --> <!-- ✅ Preserve aspect ratio --> <img src="photo.jpg" width="300" height="225"> <!-- Actual 4:3 dimensions --> <!-- ✅ CSS object-fit for flexibility --> <img src="photo.jpg" style="width: 300px; height: 200px; object-fit: cover;">
javascript// ❌ Request on page load (bad UX, often denied) navigator.geolocation.getCurrentPosition(success, error); // ✅ Request in context, after user action findNearbyButton.addEventListener('click', async () => { // Explain why you need it if (await showPermissionExplanation()) { navigator.geolocation.getCurrentPosition(success, error); } });
html<!-- Restrict powerful features --> <meta http-equiv="Permissions-Policy" content="geolocation=(), camera=(), microphone=()"> <!-- Or allow for specific origins --> <meta http-equiv="Permissions-Policy" content="geolocation=(self 'https://maps.example.com')">
npm audit)| Tool | Purpose | |------|---------| | npm audit | Dependency vulnerabilities | | SecurityHeaders.com | Header analysis | | W3C Validator | HTML validation | | Lighthouse | Best practices audit | | Observatory | Security scan |
Other measured skills in the registry, with their headline benchmark lift.