Learn production deployment strategies, build optimization, environment configuration, and monitoring for React applications.
Learn production deployment strategies, build optimization, environment configuration, and monitoring for React applications.
Master build optimization techniques to create fast, efficient production builds of your React applications.
Content by: Praveen Kumar
MERN Stack Developer
Learn to configure Webpack for optimal production builds with code splitting, tree shaking, and asset optimization.
// Dynamic imports for code splitting
const LazyComponent = React.lazy(() => import('./LazyComponent'));
// Route-based code splitting
const Home = React.lazy(() => import('./pages/Home'));
const About = React.lazy(() => import('./pages/About'));
// Component-based code splitting
const HeavyComponent = React.lazy(() =>
import('./HeavyComponent').then(module => ({
default: module.HeavyComponent
}))
);// webpack-bundle-analyzer setup
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
openAnalyzer: false,
reportFilename: 'bundle-report.html'
})
]
};
// Package.json script
"scripts": {
"analyze": "npm run build && npx webpack-bundle-analyzer build/static/js/*.js"
}// Image optimization
import { optimize } from 'webpack-image-loader';
module.exports = {
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].[hash:8].[ext]'
}
},
{
loader: 'image-webpack-loader',
options: {
mozjpeg: { progressive: true, quality: 65 },
optipng: { enabled: false },
pngquant: { quality: [0.65, 0.90], speed: 4 },
gifsicle: { interlaced: false }
}
}
]
}
]
}
};// Complete webpack configuration for production
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
mode: 'production',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'static/js/[name].[contenthash:8].js',
chunkFilename: 'static/js/[name].[contenthash:8].chunk.js',
clean: true
},
optimization: {
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
parse: { ecma: 8 },
compress: { ecma: 5 },
mangle: { ecma: 5 },
output: { ecma: 5 }
}
}),
new OptimizeCSSAssetsPlugin()
],
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react']
}
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './public/index.html',
minify: {
removeComments: true,
collapseWhitespace: true,
removeRedundantAttributes: true
}
}),
new MiniCssExtractPlugin({
filename: 'static/css/[name].[contenthash:8].css'
})
]
};Test your understanding of this topic:
Learn to configure different environments (development, staging, production) with proper environment variables and configuration management.
Content by: Sachin Patel
Node.js Developer
Master environment variable management for different deployment environments with proper security practices.
// .env files for different environments
// .env.development
REACT_APP_API_URL=http://localhost:3001
REACT_APP_DEBUG=true
REACT_APP_VERSION=1.0.0
// .env.production
REACT_APP_API_URL=https://api.myapp.com
REACT_APP_DEBUG=false
REACT_APP_VERSION=1.0.0
// .env.staging
REACT_APP_API_URL=https://staging-api.myapp.com
REACT_APP_DEBUG=true
REACT_APP_VERSION=1.0.0-staging// config/index.js
const config = {
development: {
apiUrl: process.env.REACT_APP_API_URL || 'http://localhost:3001',
debug: process.env.REACT_APP_DEBUG === 'true',
version: process.env.REACT_APP_VERSION || '1.0.0'
},
production: {
apiUrl: process.env.REACT_APP_API_URL,
debug: false,
version: process.env.REACT_APP_VERSION
},
staging: {
apiUrl: process.env.REACT_APP_API_URL,
debug: process.env.REACT_APP_DEBUG === 'true',
version: process.env.REACT_APP_VERSION
}
};
export default config[process.env.NODE_ENV || 'development'];// Feature flags implementation
const features = {
newDashboard: process.env.REACT_APP_FEATURE_NEW_DASHBOARD === 'true',
betaFeatures: process.env.REACT_APP_FEATURE_BETA === 'true',
analytics: process.env.REACT_APP_FEATURE_ANALYTICS === 'true'
};
export const isFeatureEnabled = (feature) => {
return features[feature] || false;
};
// Usage in components
if (isFeatureEnabled('newDashboard')) {
return <NewDashboard />;
}
return <OldDashboard />;// Complete environment configuration system
import { z } from 'zod';
// Environment schema validation
const envSchema = z.object({
NODE_ENV: z.enum(['development', 'production', 'staging']),
REACT_APP_API_URL: z.string().url(),
REACT_APP_DEBUG: z.string().transform(val => val === 'true'),
REACT_APP_VERSION: z.string(),
REACT_APP_FEATURES: z.string().optional()
});
// Parse and validate environment variables
const parseEnv = () => {
try {
return envSchema.parse(process.env);
} catch (error) {
console.error('Invalid environment configuration:', error);
throw new Error('Environment configuration is invalid');
}
};
// Configuration factory
const createConfig = () => {
const env = parseEnv();
return {
api: {
baseUrl: env.REACT_APP_API_URL,
timeout: env.NODE_ENV === 'production' ? 10000 : 30000
},
app: {
version: env.REACT_APP_VERSION,
debug: env.REACT_APP_DEBUG,
environment: env.NODE_ENV
},
features: {
newDashboard: env.REACT_APP_FEATURES?.includes('new-dashboard') || false,
betaFeatures: env.REACT_APP_FEATURES?.includes('beta') || false
}
};
};
export const config = createConfig();
export default config;Test your understanding of this topic:
Learn various deployment strategies including static hosting, containerization, and cloud deployment options.
Content by: Parth Patel
Node.js Developer
Deploy React applications to static hosting services like Netlify, Vercel, and AWS S3 with proper configuration.
# netlify.toml
[build]
publish = "build"
command = "npm run build"
[build.environment]
NODE_VERSION = "18"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
[headers]
for = "/static/*"
[headers.values]
Cache-Control = "public, max-age=31536000, immutable"# Dockerfile for React app
FROM node:18-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]# .github/workflows/deploy.yml
name: Deploy to Production
on:
push:
branches: [main]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test -- --coverage --watchAll=false
- name: Build application
run: npm run build
env:
REACT_APP_API_URL: ${{ secrets.REACT_APP_API_URL }}
- name: Deploy to AWS S3
uses: aws-actions/configure-aws-credentials@v2
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- name: Upload to S3
run: aws s3 sync build/ s3://my-react-app --delete// Blue-green deployment strategy
const deploymentConfig = {
blue: {
version: '1.0.0',
url: 'https://blue.myapp.com',
traffic: 0
},
green: {
version: '1.1.0',
url: 'https://green.myapp.com',
traffic: 100
}
};
// Gradual traffic shifting
const shiftTraffic = (from, to, percentage) => {
// Implementation for traffic shifting
console.log(`Shifting ${percentage}% traffic from ${from} to ${to}`);
};// Complete deployment configuration
# docker-compose.yml
version: '3.8'
services:
react-app:
build: .
ports:
- "3000:80"
environment:
- NODE_ENV=production
- REACT_APP_API_URL=http://api:3001
depends_on:
- nginx
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
- ./build:/usr/share/nginx/html
# nginx.conf
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
gzip on;
gzip_types text/plain text/css application/json application/javascript;
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
}
# package.json scripts
{
"scripts": {
"build": "react-scripts build",
"build:docker": "docker build -t react-app .",
"deploy:staging": "npm run build && aws s3 sync build/ s3://staging-bucket",
"deploy:production": "npm run build && aws s3 sync build/ s3://production-bucket"
}
}Test your understanding of this topic:
Implement comprehensive monitoring, analytics, and error tracking for production React applications.
Content by: Bansi Patel
Node.js Developer
Set up error tracking and monitoring to catch and analyze errors in production applications.
// Sentry setup
import * as Sentry from '@sentry/react';
import { BrowserTracing } from '@sentry/tracing';
Sentry.init({
dsn: process.env.REACT_APP_SENTRY_DSN,
integrations: [
new BrowserTracing(),
],
tracesSampleRate: 1.0,
environment: process.env.NODE_ENV,
});
// Error boundary with Sentry
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 <div>Something went wrong.</div>;
}
return this.props.children;
}
}// Performance monitoring
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
const sendToAnalytics = (metric) => {
// Send to your analytics service
gtag('event', metric.name, {
value: Math.round(metric.value),
event_label: metric.id,
non_interaction: true,
});
};
// Measure Core Web Vitals
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);// Google Analytics 4 setup
import ReactGA from 'react-ga4';
const GA_TRACKING_ID = process.env.REACT_APP_GA_TRACKING_ID;
ReactGA.initialize(GA_TRACKING_ID);
// Track page views
const trackPageView = (path) => {
ReactGA.send({ hitType: 'pageview', page: path });
};
// Track custom events
const trackEvent = (action, category, label, value) => {
ReactGA.event({
action,
category,
label,
value
});
};
// Usage in components
useEffect(() => {
trackPageView(window.location.pathname);
}, []);// Health check endpoint
const healthCheck = {
status: 'healthy',
timestamp: new Date().toISOString(),
version: process.env.REACT_APP_VERSION,
environment: process.env.NODE_ENV,
uptime: process.uptime(),
memory: process.memoryUsage()
};
// API health monitoring
const checkAPIHealth = async () => {
try {
const response = await fetch('/api/health');
const data = await response.json();
return data.status === 'healthy';
} catch (error) {
console.error('API health check failed:', error);
return false;
}
};// Complete monitoring and analytics system
import React, { useEffect } from 'react';
import * as Sentry from '@sentry/react';
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
// Performance monitoring
const initPerformanceMonitoring = () => {
const sendToAnalytics = (metric) => {
// Send to your analytics service
if (window.gtag) {
window.gtag('event', metric.name, {
value: Math.round(metric.value),
event_label: metric.id,
non_interaction: true,
});
}
};
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getFCP(sendToAnalytics);
getLCP(sendToAnalytics);
getTTFB(sendToAnalytics);
};
// Error tracking
const initErrorTracking = () => {
Sentry.init({
dsn: process.env.REACT_APP_SENTRY_DSN,
environment: process.env.NODE_ENV,
beforeSend(event) {
// Filter out development errors
if (process.env.NODE_ENV === 'development') {
return null;
}
return event;
}
});
};
// Analytics tracking
const initAnalytics = () => {
if (process.env.REACT_APP_GA_TRACKING_ID) {
// Initialize Google Analytics
window.gtag('config', process.env.REACT_APP_GA_TRACKING_ID, {
page_title: document.title,
page_location: window.location.href
});
}
};
// Custom hook for monitoring
const useMonitoring = () => {
useEffect(() => {
initPerformanceMonitoring();
initErrorTracking();
initAnalytics();
}, []);
const trackEvent = (action, category, label, value) => {
if (window.gtag) {
window.gtag('event', action, {
event_category: category,
event_label: label,
value: value
});
}
};
const trackError = (error, context = {}) => {
Sentry.captureException(error, {
extra: context
});
};
return { trackEvent, trackError };
};
export default useMonitoring;Test your understanding of this topic:
Continue your learning journey and master the next set of concepts.
Back to Course Overview