โก Best Practices for Web Developers
Professional coding standards, security, performance, and workflow optimization
Code Quality & Standards
๐ Naming Conventions
JavaScript/TypeScript:
camelCasefor variables and functions:getUserData(),totalPricePascalCasefor classes and components:UserProfile,ProductCardCONSTANT_CASEfor constants:MAX_RETRY_COUNT,API_BASE_URL- Meaningful names:
fetchUserOrders()notgetUserStuff()
CSS:
kebab-casefor classes:.nav-link,.product-card- BEM methodology:
.block__element--modifier - Descriptive names:
.primary-buttonnot.btn1
Files & Folders:
kebab-casefor files:user-profile.js,product-detail.html- Lowercase folder names:
components/,utils/,assets/
๐งน Clean Code Principles
- DRY (Don't Repeat Yourself): Extract repeated code into functions/components
- KISS (Keep It Simple, Stupid): Simple solutions over clever complexity
- YAGNI (You Aren't Gonna Need It): Don't build features you don't need yet
- Single Responsibility: Each function/component does one thing well
- Meaningful Names: Code should be self-documenting
- Comments: Explain WHY, not WHAT (code shows what)
- Consistent Formatting: Use linters (ESLint, Prettier)
๐ฏ Function Best Practices
โ Good:
// Pure function, single responsibility, clear name
function calculateTotalPrice(items, taxRate) {
const subtotal = items.reduce((sum, item) => sum + item.price, 0);
return subtotal * (1 + taxRate);
}โ Bad:
// Does too much, unclear name, side effects
function doStuff(items) {
let t = 0;
for (let i = 0; i < items.length; i++) {
t += items[i].price;
console.log(items[i]); // side effect
}
return t * 1.08; // magic number
}Security Best Practices
๐ Never Trust User Input
Input Validation:
// โ
Good: Validate and sanitize
function processEmail(email) {
// Validate format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
throw new Error('Invalid email format');
}
// Sanitize
const sanitized = email.trim().toLowerCase();
return sanitized;
}Prevent XSS Attacks:
// โ NEVER do this (XSS vulnerability)
element.innerHTML = userInput;
// โ
Use textContent or sanitize
element.textContent = userInput;
// โ
Or use DOMPurify library
element.innerHTML = DOMPurify.sanitize(userInput);๐ Sensitive Data Handling
- โ Never hardcode API keys, passwords, or secrets in code
- โ
Use environment variables (
process.env.API_KEY) - โ Never log sensitive data to console
- โ Never commit
.envfiles to version control - โ
Add
.envto.gitignore - โ Use secrets management (AWS Secrets Manager, Azure Key Vault)
- โ Hash passwords with bcrypt/Argon2, never store plain text
- โ Always use HTTPS for transmitting sensitive data
Performance Optimization
โก Frontend Performance
Image Optimization:
- Use modern formats (WebP, AVIF) with fallbacks
- Compress images (80-85% quality sufficient)
- Use responsive images with
srcset - Lazy load below-the-fold images
- Use CDN for static assets
Code Optimization:
- Minify CSS, JavaScript, HTML for production
- Remove unused CSS (PurgeCSS)
- Code splitting (load only what's needed)
- Tree shaking (remove dead code)
- Use compression (gzip, Brotli)
Loading Performance:
- Minimize HTTP requests (bundle assets)
- Use browser caching headers
- Defer non-critical JavaScript
- Inline critical CSS
- Use preload for critical resources
๐ Measuring Performance
Core Web Vitals (Google Ranking Factors):
- LCP (Largest Contentful Paint): < 2.5s (page load speed)
- FID (First Input Delay): < 100ms (interactivity)
- CLS (Cumulative Layout Shift): < 0.1 (visual stability)
Tools:
- Google PageSpeed Insights
- Lighthouse (Chrome DevTools)
- WebPageTest
- Chrome DevTools Performance tab
Accessibility (A11y)
โฟ WCAG 2.1 Compliance
Semantic HTML:
<!-- โ Bad -->
<div onclick="submitForm()">Submit</div>
<!-- โ
Good -->
<button type="submit">Submit</button>Alt Text for Images:
<!-- โ Bad -->
<img src="product.jpg">
<!-- โ
Good -->
<img src="product.jpg" alt="Blue running shoes with white sole">ARIA Labels:
<nav aria-label="Main navigation">
<button aria-label="Close dialog" aria-expanded="false">
<span aria-hidden="true">ร</span>
</button>
</nav>Keyboard Navigation:
- All interactive elements accessible via Tab key
- Visible focus indicators
- Skip to main content link
- Logical tab order
- Escape key closes modals/dropdowns
API Design Best Practices
๐ RESTful API Standards
HTTP Methods:
GET- Retrieve data (idempotent, no side effects)POST- Create new resourcePUT- Update entire resourcePATCH- Partial updateDELETE- Remove resource
Status Codes:
200 OK- Successful GET, PUT, PATCH, DELETE201 Created- Successful POST204 No Content- Successful DELETE with no response body400 Bad Request- Invalid client request401 Unauthorized- Authentication required403 Forbidden- Authenticated but not authorized404 Not Found- Resource doesn't exist500 Internal Server Error- Server error
Endpoint Naming:
โ
Good: RESTful, plural nouns
GET /api/users
GET /api/users/123
POST /api/users
PUT /api/users/123
DELETE /api/users/123
โ Bad: Verbs in URLs, inconsistent
GET /api/getUsers
POST /api/createUser
GET /api/user/123Version Control Best Practices
๐ฆ Git Workflow
Commit Messages:
โ
Good: Clear, descriptive, imperative mood
feat: Add user authentication with JWT
fix: Resolve mobile navigation overflow bug
docs: Update API documentation for v2.0
refactor: Extract validation logic into utils
โ Bad: Vague, unclear
updated stuff
fix bug
changes
wipBranching Strategy:
main- Production-ready codedevelop- Integration branch for featuresfeature/feature-name- New featuresbugfix/bug-description- Bug fixeshotfix/critical-fix- Emergency production fixes
.gitignore Essentials:
node_modules/
.env
.env.local
dist/
build/
*.log
.DS_Store
.vscode/Testing Best Practices
๐งช Testing Strategy
Test Pyramid:
- 70% Unit Tests: Test individual functions/components
- 20% Integration Tests: Test component interactions
- 10% E2E Tests: Test full user workflows
What to Test:
- โ Business logic and calculations
- โ Edge cases and error handling
- โ User interactions and form validation
- โ API integrations
- โ Don't test framework internals
- โ Don't test third-party libraries
Documentation Best Practices
๐ Code Documentation
README.md Should Include:
- Project description and purpose
- Installation instructions
- Usage examples
- Configuration options
- API documentation or link
- Contributing guidelines
- License information
Code Comments:
// โ
Good: Explain WHY, not WHAT
// Using setTimeout to debounce rapid API calls
// Prevents rate limit errors from search-as-you-type
setTimeout(() => fetchResults(query), 300);
// โ Bad: Stating the obvious
// Set timeout to 300
setTimeout(() => fetchResults(query), 300);Deployment Best Practices
๐ Production Checklist
- โ Environment variables configured
- โ HTTPS enabled with valid SSL certificate
- โ Assets minified and compressed
- โ Error logging configured (Sentry, LogRocket)
- โ Database backups automated
- โ Security headers configured
- โ Rate limiting implemented
- โ CDN configured for static assets
- โ Monitoring and alerts set up
- โ Rollback plan documented
- โ Performance tested under load
- โ Accessibility tested (WCAG 2.1 AA)
- โ Cross-browser testing completed
- โ Mobile responsiveness verified
- โ SEO meta tags configured
๐ ๏ธ Use Professional Tools
Apply these best practices with our privacy-focused developer utilities: