Learn production deployment strategies, code optimization, security best practices, and monitoring for JavaScript applications.
Learn production deployment strategies, code optimization, security best practices, and monitoring for JavaScript applications.
Learn advanced code optimization techniques for production JavaScript applications
Content by: Kriyansh Khunt
MERN Stack Developer
Optimize JavaScript code for better performance, smaller bundle sizes, and faster execution.
// webpack.config.js - Bundle optimization
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\/]node_modules[\/]/,
name: 'vendors',
chunks: 'all'
}
}
},
usedExports: true,
sideEffects: false
},
plugins: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true,
drop_debugger: true
}
}
})
]
};// ES6 modules for tree shaking
// utils.js
export const add = (a, b) => a + b;
export const multiply = (a, b) => a * b;
export const divide = (a, b) => a / b;
// main.js
import { add } from './utils.js';
// Only 'add' function will be included in bundle
// CommonJS (not tree-shakeable)
const utils = require('./utils');
// Entire utils module will be included// Dynamic imports for lazy loading
const loadModule = async () => {
const module = await import('./heavy-module.js');
return module.default;
};
// React lazy loading
const LazyComponent = React.lazy(() => import('./HeavyComponent'));
// Route-based code splitting
const routes = [
{
path: '/',
component: () => import('./pages/Home')
},
{
path: '/about',
component: () => import('./pages/About')
}
];// Memory leak prevention
class DataProcessor {
constructor() {
this.cache = new Map();
this.cleanupInterval = setInterval(() => {
this.cleanupCache();
}, 60000); // Clean every minute
}
processData(data) {
const key = JSON.stringify(data);
if (this.cache.has(key)) {
return this.cache.get(key);
}
const result = this.expensiveOperation(data);
this.cache.set(key, result);
return result;
}
cleanupCache() {
// Remove old entries
const now = Date.now();
for (const [key, value] of this.cache) {
if (now - value.timestamp > 300000) { // 5 minutes
this.cache.delete(key);
}
}
}
destroy() {
clearInterval(this.cleanupInterval);
this.cache.clear();
}
}// Performance optimization utility
class PerformanceOptimizer {
static debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
static throttle(func, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
static memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
static imageOptimizer() {
return {
lazyLoad: (img) => {
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const image = entry.target;
image.src = image.dataset.src;
observer.unobserve(image);
}
});
});
observer.observe(img);
},
compress: (file, quality = 0.8) => {
return new Promise((resolve) => {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
canvas.toBlob(resolve, 'image/jpeg', quality);
};
img.src = URL.createObjectURL(file);
});
}
};
}
}Test your understanding of this topic:
Implement security best practices for production JavaScript applications
Content by: Praveen Kumar
MERN Stack Developer
Validate and sanitize all user inputs to prevent security vulnerabilities.
// XSS prevention utilities
class XSSProtection {
static sanitizeHTML(input) {
const div = document.createElement('div');
div.textContent = input;
return div.innerHTML;
}
static escapeHTML(input) {
return input
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
static validateInput(input, type) {
const patterns = {
email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
phone: /^\+?[1-9]\d{1,14}$/,
alphanumeric: /^[a-zA-Z0-9]+$/,
url: /^https?:\/\/.+/
};
return patterns[type] ? patterns[type].test(input) : false;
}
}// CSRF token management
class CSRFProtection {
static generateToken() {
const array = new Uint8Array(32);
crypto.getRandomValues(array);
return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}
static setToken() {
const token = this.generateToken();
sessionStorage.setItem('csrf_token', token);
return token;
}
static validateToken(token) {
const storedToken = sessionStorage.getItem('csrf_token');
return token === storedToken;
}
static addToForm(form) {
const token = this.setToken();
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'csrf_token';
input.value = token;
form.appendChild(input);
}
}// CSP implementation
const cspConfig = {
'default-src': ["'self'"],
'script-src': ["'self'", "'unsafe-inline'"],
'style-src': ["'self'", "'unsafe-inline'"],
'img-src': ["'self'", "data:", "https:"],
'connect-src': ["'self'"],
'font-src': ["'self'"],
'object-src': ["'none'"],
'media-src': ["'self'"],
'frame-src': ["'none'"]
};
// Set CSP header
function setCSP() {
const csp = Object.entries(cspConfig)
.map(([key, value]) => `${key} ${value.join(' ')}`)
.join('; ');
document.querySelector('meta[http-equiv="Content-Security-Policy"]')
?.setAttribute('content', csp);
}// Secure API client
class SecureAPIClient {
constructor(baseURL, apiKey) {
this.baseURL = baseURL;
this.apiKey = apiKey;
}
async request(endpoint, options = {}) {
const url = new URL(endpoint, this.baseURL);
const config = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.apiKey}`,
'X-Requested-With': 'XMLHttpRequest'
},
...options
};
// Add CSRF token if available
const csrfToken = sessionStorage.getItem('csrf_token');
if (csrfToken) {
config.headers['X-CSRF-Token'] = csrfToken;
}
try {
const response = await fetch(url, config);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
}// Security vulnerability scanner
class SecurityScanner {
static scanDOM() {
const vulnerabilities = [];
// Check for inline scripts
const inlineScripts = document.querySelectorAll('script:not([src])');
if (inlineScripts.length > 0) {
vulnerabilities.push({
type: 'XSS',
severity: 'high',
message: 'Inline scripts detected',
elements: Array.from(inlineScripts)
});
}
// Check for eval usage
const scripts = document.querySelectorAll('script[src]');
scripts.forEach(script => {
fetch(script.src)
.then(response => response.text())
.then(code => {
if (code.includes('eval(')) {
vulnerabilities.push({
type: 'Code Injection',
severity: 'critical',
message: 'eval() usage detected',
file: script.src
});
}
});
});
return vulnerabilities;
}
static checkHTTPS() {
if (location.protocol !== 'https:') {
return {
type: 'Security',
severity: 'high',
message: 'Site not served over HTTPS'
};
}
return null;
}
static validateHeaders() {
const issues = [];
// Check for security headers
const requiredHeaders = [
'X-Content-Type-Options',
'X-Frame-Options',
'X-XSS-Protection'
];
// Note: This would need to be implemented server-side
// or through a security scanning service
return issues;
}
static generateReport() {
const vulnerabilities = this.scanDOM();
const httpsIssue = this.checkHTTPS();
const headerIssues = this.validateHeaders();
return {
timestamp: new Date().toISOString(),
vulnerabilities: [
...vulnerabilities,
...(httpsIssue ? [httpsIssue] : []),
...headerIssues
],
summary: {
total: vulnerabilities.length + (httpsIssue ? 1 : 0) + headerIssues.length,
critical: vulnerabilities.filter(v => v.severity === 'critical').length,
high: vulnerabilities.filter(v => v.severity === 'high').length,
medium: vulnerabilities.filter(v => v.severity === 'medium').length
}
};
}
}Test your understanding of this topic:
Learn various deployment strategies for JavaScript applications
Content by: Sachin Patel
Node.js Developer
Deploy static JavaScript applications to CDNs and static hosting services.
# netlify.toml
[build]
publish = "dist"
command = "npm run build"
[build.environment]
NODE_VERSION = "18"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
# Build script
npm run build
netlify deploy --prod --dir=dist// vercel.json
{
"builds": [
{
"src": "package.json",
"use": "@vercel/static-build",
"config": {
"distDir": "dist"
}
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/index.html"
}
]
}
# Deploy
vercel --prod# Dockerfile
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
# nginx.conf
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: js-app
spec:
replicas: 3
selector:
matchLabels:
app: js-app
template:
metadata:
labels:
app: js-app
spec:
containers:
- name: js-app
image: js-app:latest
ports:
- containerPort: 80
resources:
requests:
memory: "64Mi"
cpu: "250m"
limits:
memory: "128Mi"
cpu: "500m"
---
apiVersion: v1
kind: Service
metadata:
name: js-app-service
spec:
selector:
app: js-app
ports:
- port: 80
targetPort: 80
type: LoadBalancer// deployment-pipeline.js
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
class DeploymentPipeline {
constructor(config) {
this.config = config;
this.stages = ['build', 'test', 'deploy'];
}
async run() {
console.log('๐ Starting deployment pipeline...');
for (const stage of this.stages) {
try {
await this.executeStage(stage);
console.log(`โ
${stage} completed successfully`);
} catch (error) {
console.error(`โ ${stage} failed:`, error.message);
throw error;
}
}
console.log('๐ Deployment completed successfully!');
}
async executeStage(stage) {
switch (stage) {
case 'build':
await this.build();
break;
case 'test':
await this.test();
break;
case 'deploy':
await this.deploy();
break;
}
}
async build() {
console.log('๐จ Building application...');
execSync('npm run build', { stdio: 'inherit' });
// Verify build output
const distPath = path.join(process.cwd(), 'dist');
if (!fs.existsSync(distPath)) {
throw new Error('Build output not found');
}
}
async test() {
console.log('๐งช Running tests...');
execSync('npm test', { stdio: 'inherit' });
}
async deploy() {
console.log('๐ Deploying application...');
switch (this.config.deployment.target) {
case 'netlify':
await this.deployToNetlify();
break;
case 'vercel':
await this.deployToVercel();
break;
case 'docker':
await this.deployWithDocker();
break;
default:
throw new Error('Unknown deployment target');
}
}
async deployToNetlify() {
execSync('netlify deploy --prod --dir=dist', { stdio: 'inherit' });
}
async deployToVercel() {
execSync('vercel --prod', { stdio: 'inherit' });
}
async deployWithDocker() {
execSync('docker build -t js-app .', { stdio: 'inherit' });
execSync('docker run -d -p 3000:80 js-app', { stdio: 'inherit' });
}
}
// Usage
const config = {
deployment: {
target: 'netlify'
}
};
const pipeline = new DeploymentPipeline(config);
pipeline.run().catch(console.error);Test your understanding of this topic:
Implement monitoring and analytics for production JavaScript applications
Content by: Parth Patel
Node.js Developer
Implement comprehensive error tracking and monitoring for production applications.
// Sentry setup
import * as Sentry from '@sentry/browser';
Sentry.init({
dsn: 'YOUR_SENTRY_DSN',
environment: process.env.NODE_ENV,
tracesSampleRate: 1.0,
});
// Error boundary
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
Sentry.captureException(error, {
contexts: {
react: {
componentStack: errorInfo.componentStack
}
}
});
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}// Performance monitoring
class PerformanceMonitor {
constructor() {
this.metrics = new Map();
this.observers = [];
}
startTiming(name) {
this.metrics.set(name, performance.now());
}
endTiming(name) {
const startTime = this.metrics.get(name);
if (startTime) {
const duration = performance.now() - startTime;
this.recordMetric(name, duration);
this.metrics.delete(name);
}
}
recordMetric(name, value) {
const metric = {
name,
value,
timestamp: Date.now()
};
this.observers.forEach(observer => {
observer(metric);
});
}
addObserver(observer) {
this.observers.push(observer);
}
getMetrics() {
return Array.from(this.metrics.entries());
}
}// Analytics tracking
class Analytics {
constructor(config) {
this.config = config;
this.events = [];
this.sessionId = this.generateSessionId();
}
track(event, properties = {}) {
const eventData = {
event,
properties: {
...properties,
sessionId: this.sessionId,
timestamp: Date.now(),
url: window.location.href,
userAgent: navigator.userAgent
}
};
this.events.push(eventData);
this.sendEvent(eventData);
}
pageView(page) {
this.track('page_view', { page });
}
userAction(action, element) {
this.track('user_action', { action, element });
}
error(error, context) {
this.track('error', { error: error.message, context });
}
sendEvent(eventData) {
if (this.config.endpoint) {
fetch(this.config.endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(eventData)
}).catch(console.error);
}
}
generateSessionId() {
return 'session_' + Math.random().toString(36).substr(2, 9);
}
}// Health check system
class HealthChecker {
constructor() {
this.checks = new Map();
this.status = 'unknown';
}
addCheck(name, checkFunction) {
this.checks.set(name, checkFunction);
}
async runChecks() {
const results = {};
let allHealthy = true;
for (const [name, check] of this.checks) {
try {
const result = await check();
results[name] = {
status: 'healthy',
result
};
} catch (error) {
results[name] = {
status: 'unhealthy',
error: error.message
};
allHealthy = false;
}
}
this.status = allHealthy ? 'healthy' : 'unhealthy';
return {
status: this.status,
checks: results,
timestamp: new Date().toISOString()
};
}
getStatus() {
return {
status: this.status,
timestamp: new Date().toISOString()
};
}
}// Complete monitoring dashboard
class MonitoringDashboard {
constructor() {
this.performanceMonitor = new PerformanceMonitor();
this.analytics = new Analytics({ endpoint: '/api/analytics' });
this.healthChecker = new HealthChecker();
this.setupHealthChecks();
this.setupPerformanceTracking();
this.renderDashboard();
}
setupHealthChecks() {
this.healthChecker.addCheck('api', async () => {
const response = await fetch('/api/health');
return response.ok;
});
this.healthChecker.addCheck('database', async () => {
// Simulate database check
return true;
});
}
setupPerformanceTracking() {
this.performanceMonitor.addObserver((metric) => {
this.analytics.track('performance_metric', metric);
});
}
renderDashboard() {
const dashboard = document.createElement('div');
dashboard.id = 'monitoring-dashboard';
dashboard.innerHTML = `
<div class="dashboard">
<h2>Application Monitoring</h2>
<div id="health-status">Checking health...</div>
<div id="performance-metrics">Performance metrics will appear here</div>
<div id="error-log">Error log will appear here</div>
</div>
`;
document.body.appendChild(dashboard);
this.startMonitoring();
}
async startMonitoring() {
// Health checks every 30 seconds
setInterval(async () => {
const health = await this.healthChecker.runChecks();
this.updateHealthStatus(health);
}, 30000);
// Performance monitoring
this.performanceMonitor.startTiming('page_load');
window.addEventListener('load', () => {
this.performanceMonitor.endTiming('page_load');
});
}
updateHealthStatus(health) {
const statusElement = document.getElementById('health-status');
statusElement.innerHTML = `
<div class="health-status ${health.status}">
<h3>Health Status: ${health.status.toUpperCase()}</h3>
<div class="checks">
${Object.entries(health.checks).map(([name, check]) => `
<div class="check ${check.status}">
${name}: ${check.status}
</div>
`).join('')}
</div>
</div>
`;
}
}Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Back to Course Overview