Modern Web Development Best Practices
Even a small web project benefits from a short checklist. Performance, security, accessibility, and user experience are connected decisions, so this guide treats them as part of the same implementation loop.
Performance Optimization
1. Image Optimization
Images often account for the largest portion of page weight:
<!-- Use modern formats -->
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Description" loading="lazy">
</picture>
2. Code Splitting
Split your JavaScript bundles:
// Dynamic imports
const LazyComponent = React.lazy(() => import('./LazyComponent'));
// Route-based splitting
const routes = [
{
path: '/dashboard',
component: () => import('./Dashboard')
}
];
3. Caching Strategies
Implement proper caching:
// Service Worker caching
self.addEventListener('fetch', event => {
if (event.request.destination === 'image') {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
}
});
Security Best Practices
1. Input Validation
Always validate and sanitize user input:
// Server-side validation
const { body, validationResult } = require('express-validator');
app.post('/contact', [
body('email').isEmail().normalizeEmail(),
body('message').trim().isLength({ min: 10 })
], (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process form...
});
2. HTTPS Everywhere
Always use HTTPS in production:
// Terminate TLS and redirect HTTP at a trusted reverse proxy.
// In Express, add HSTS after HTTPS is correctly configured:
app.use(helmet.hsts({ maxAge: 31536000, includeSubDomains: true }));
3. Content Security Policy
Implement CSP headers:
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'"],
scriptSrc: ["'self'"],
scriptSrcAttr: ["'none'"],
imgSrc: ["'self'", "data:"]
}
}
}));
Accessibility (a11y)
1. Semantic HTML
Use proper HTML elements:
<main>
<header>
<nav aria-label="Main navigation">
<ul>
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
</header>
<article>
<h1>Article Title</h1>
<p>Article content...</p>
</article>
</main>
2. ARIA Labels
Provide context for screen readers:
<button aria-label="Close dialog" aria-expanded="false">
<span aria-hidden="true">×</span>
</button>
3. Keyboard Navigation
Ensure all functionality is keyboard accessible:
// Handle keyboard events
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeModal();
}
});
User Experience
1. Progressive Enhancement
Build core functionality first:
<!-- Basic form -->
<form action="/contact" method="POST">
<input type="email" name="email" required>
<textarea name="message" required></textarea>
<button type="submit">Send</button>
</form>
<!-- Enhanced with JavaScript -->
<script>
// Add AJAX functionality
document.querySelector('form').addEventListener('submit', handleAjaxSubmit);
</script>
2. Error Handling
Provide clear error messages:
try {
const response = await fetch('/api/data');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
} catch (error) {
showErrorMessage('Failed to load data. Please try again.');
}
3. Loading States
Show loading indicators:
async function submitForm(formData) {
const submitBtn = document.querySelector('#submit-btn');
const originalText = submitBtn.textContent;
submitBtn.textContent = 'Sending...';
submitBtn.disabled = true;
try {
await fetch('/contact', {
method: 'POST',
body: formData
});
showSuccessMessage('Message sent successfully!');
} finally {
submitBtn.textContent = originalText;
submitBtn.disabled = false;
}
}
Development Workflow
1. Version Control
Use Git effectively:
# Feature branch workflow
git checkout -b feature/new-component
git add .
git commit -m "feat: add new component"
git push origin feature/new-component
2. Code Quality
Implement linting and formatting:
// .eslintrc.json
{
"extends": ["eslint:recommended", "@typescript-eslint/recommended"],
"rules": {
"no-console": "warn",
"prefer-const": "error"
}
}
3. Testing
Write tests for critical functionality:
// Jest test example
describe('Contact Form', () => {
test('validates email input', () => {
const email = 'invalid-email';
expect(validateEmail(email)).toBe(false);
});
test('submits form with valid data', async () => {
const formData = new FormData();
formData.append('email', '[email protected]');
formData.append('message', 'Test message');
const response = await submitForm(formData);
expect(response.success).toBe(true);
});
});
Conclusion
Following these best practices will help you build more robust, secure, and user-friendly web applications. Remember that web development is constantly evolving, so stay updated with the latest trends and technologies.
Resources
- Web.dev - Google’s web development guide
- MDN Web Docs - Comprehensive web documentation
- A11y Project - Accessibility resources
Keep learning, keep building, and always prioritize user experience!