Unit 5: Performance, SEO, and Deployment
I. Orientation
Modern web application development treats performance, discoverability, reliability, and deployment as connected engineering concerns. A fast application reduces user abandonment, effective SEO makes content indexable, and a correctly configured production deployment delivers the tested application safely to users.
- Governing principle: Minimize the amount of work required to render useful content, transfer resources, execute JavaScript, and respond to user actions.
- Performance measures: Core Web Vitals emphasize Largest Contentful Paint (LCP), Interaction to Next Paint (INP), and Cumulative Layout Shift (CLS).
- SEO assumption: Search engines must be able to discover, crawl, interpret, and index relevant content.
- Build convention: Development builds prioritize debugging; production builds prioritize optimized output, caching, security, and stability.
- Deployment convention: Configuration, logs, monitoring, and failure handling are part of the application rather than afterthoughts.
II. Image Optimization — Efficient Visual Resources
A. Image Optimization
Image optimization reduces image transfer size and rendering cost while preserving acceptable visual quality. Images commonly dominate a web page’s byte budget, especially on mobile networks.
- Format selection: Use AVIF or WebP for photographs and complex illustrations; use SVG for scalable interface icons and logos; use PNG when lossless transparency is essential.
- Responsive dimensions: Serve an image close to its rendered size instead of downloading a 3000-pixel image for a 300-pixel container.
HTML<img src="/hero-800.webp" srcset="/hero-400.webp 400w, /hero-800.webp 800w, /hero-1600.webp 1600w" sizes="(max-width: 600px) 100vw, 800px" width="800" height="450" alt="Product dashboard" />
srcsetlists candidate files,sizesdescribes layout width, andaltprovides accessible text. - Layout stability:
widthandheight, or CSSaspect-ratio, reserve space before loading and reduce CLS. - Loading priority: Load the above-the-fold LCP image eagerly when necessary; use
loading="lazy"for below-the-fold images. - Compression balance: Lossy compression lowers bytes but can introduce artifacts; compression should be evaluated at the displayed size.
III. Metadata API — Describing Pages to Browsers and Crawlers
A. Metadata API
A Metadata API provides structured page metadata such as titles, descriptions, canonical URLs, and social previews. In frameworks such as Next.js, metadata can be declared statically or generated dynamically from route data.
- Page identity: A title should identify the specific page, for example
Pricing | Acme, rather than repeating a generic application name. - Search description: A description summarizes page content for search-result snippets; it can influence click-through rate but does not replace useful page content.
- Static metadata: Use static metadata for pages whose title and description do not depend on a request.
TSexport const metadata = { title: "Documentation | Acme", description: "Guides for integrating the Acme API." };
titleis the browser and search title;descriptionis the summary metadata. - Dynamic metadata: Generate metadata from a product slug, article record, or other route parameter when each page has distinct content.
- Social metadata: Open Graph and Twitter/X metadata control previews containing a title, description, and image when a URL is shared.
- Canonical URL: A canonical link identifies the preferred URL when equivalent content is accessible through several paths.
IV. Code Splitting — Delivering JavaScript by Need
A. Code Splitting
Code splitting divides a large JavaScript bundle into smaller chunks so the browser downloads only code required for the current route or interaction.
- Route-level splitting: A dashboard route need not ship the JavaScript used exclusively by an administration route. Framework routers commonly create route chunks automatically.
- Dynamic imports: Load an expensive module only when its component is needed.
TSconst Chart = dynamic(() => import("./Chart"));
Chartis the loaded component, anddynamiccreates a separately fetched chunk. - Interaction-based splitting: A rich text editor, map, or payment widget can be imported when the user opens the relevant interface.
- Bundle analysis: Inspect dependency sizes because a single large library can outweigh application code. Replace unnecessary libraries or import only required functions.
- Trade-off: Splitting adds network requests and loading states. Excessive fragmentation can be slower on high-latency connections, so chunks should correspond to meaningful routes or features.
V. Lazy Loading — Deferring Nonessential Work
A. Lazy Loading
Lazy loading postpones resource loading or component rendering until it is likely to be needed. Its goal is to prioritize visible content and initial interaction.
- Images and media: Below-the-fold images can use
loading="lazy"; video can use a poster image and defer playback resources until interaction. - Components: A modal, analytics panel, or chart can be loaded when opened rather than during initial page rendering.
- Intersection Observer: The browser can detect when an element approaches the viewport, where the viewport is the visible browser region.
- Priority boundary: Do not lazy-load the main heading or the primary LCP image because delaying critical content worsens initial rendering.
- Loading state: A deferred component needs a stable placeholder, such as a fixed-height skeleton, to prevent layout movement while the request completes.
- Worked example: A 2 MB map loaded only after a user selects “View map” saves approximately 2 MB from the initial transfer, although the map still incurs a delay after that action.
VI. SEO Fundamentals — Making Content Discoverable
A. SEO Fundamentals
Search engine optimization improves how reliably crawlers discover, interpret, and rank useful application content. Technical SEO supports, but cannot substitute for, relevant and well-structured content.
- Crawlability: Provide reachable links, a valid
robots.txt, and a sitemap containing canonical public URLs. Do not block pages that should be indexed. - Semantic structure: Use one meaningful
<h1>, hierarchical headings, descriptive links, and elements such as<main>,<nav>, and<article>. - Rendered content: Search engines can process JavaScript, but server-rendered or statically generated content is generally available earlier and more reliably to crawlers.
- Canonicalization: Redirect or canonicalize duplicate paths, such as
/products?id=7and/products/7, when they represent the same content. - Accessibility relationship: Descriptive
alttext, keyboard navigation, labels, and semantic HTML improve both usability and machine interpretation. - Performance signal: A slow page can harm user engagement and search performance. LCP measures the render time of the largest visible content element; INP measures interaction responsiveness; CLS measures unexpected movement.
- Structured data: Schema.org JSON-LD can identify entities such as articles, products, or events, but markup must accurately describe visible page content.
VII. Production Build — Preparing Optimized Artifacts
A. Production Build
A production build transforms source code into deployable artifacts optimized for real users. It should expose errors before deployment and produce deterministic output from a known source revision.
- Optimization steps: Minification removes unnecessary characters, tree shaking removes unused exports, and bundling combines compatible modules.
- Framework output: A build may include server files, static assets, route manifests, and hashed JavaScript chunks. Hashed filenames allow long-term browser caching.
- Validation: The build should check types, lint rules, route generation, and required environment variables before producing a release.
- Source maps: Source maps map minified code back to source files for debugging; they should be protected if they reveal sensitive implementation details.
- Build command: A typical application uses
npm run build, wherebuildinvokes the framework’s production compiler. - Runtime distinction: Build-time variables may be embedded into bundles, while server-only variables are read at runtime. Confusing these scopes can expose secrets.
VIII. Environment Configuration — Separating Deployment Values
A. Environment Configuration
Environment configuration stores values that vary between development, testing, staging, and production without changing application source code.
- Typical variables: Database URLs, API endpoints, authentication secrets, port numbers, and feature flags are commonly environment-specific.
- Secret handling: Passwords, private keys, and tokens belong in the deployment provider’s secret store, never in Git or client-delivered JavaScript.
- Public variables: A variable intentionally exposed to browser code, such as
NEXT_PUBLIC_API_URL, must contain no secret because it becomes inspectable by every user. - Validation: Validate variables at startup and fail with a clear error when a required value is absent or malformed.
TSconst port = Number(process.env.PORT ?? 3000); if (!Number.isInteger(port)) throw new Error("PORT must be numeric");
process.env.PORTis the configured string;portis its numeric conversion. - Configuration hierarchy: Keep safe defaults in source, use local
.envfiles for development, and inject production values through the hosting platform. - Reproducibility: Record which environment and commit produced a release, while excluding secret values from logs and build output.
IX. Deployment Platforms — Running the Application
A. Deployment Platforms
Deployment platforms provide infrastructure for building, hosting, scaling, and observing an application. The correct choice depends on rendering requirements, traffic, operational control, and cost.
- Managed platforms: Services such as Vercel, Netlify, and Render automate builds, HTTPS, previews, and domain configuration. They suit teams wanting low infrastructure overhead.
- Cloud infrastructure: AWS, Google Cloud, and Azure offer containers, virtual machines, serverless functions, managed databases, and networking controls.
- Container deployment: A Docker image packages the application and runtime dependencies, reducing differences between local, staging, and production environments.
- Static hosting: A statically generated site can be served from a CDN with low latency and low operational cost, but it cannot directly perform per-request server work.
- Server rendering: Server-rendered applications require a runtime process or serverless functions and may need database connectivity, caching, and concurrency planning.
- Release workflow: Continuous integration installs dependencies, runs checks, builds the application, and deploys only successful revisions.
- Rollback: Keep a previous known-good release available so a faulty deployment can be replaced quickly.
X. Performance Monitoring — Measuring Real Behavior
A. Performance Monitoring
Performance monitoring collects measurements that reveal how an application behaves for real users and controlled test runs. Optimization should follow measured bottlenecks rather than assumptions.
- Core Web Vitals: Track LCP in seconds, INP in milliseconds, and CLS as a unitless score. These represent loading, responsiveness, and visual stability.
- Synthetic testing: Lighthouse and WebPageTest run repeatable tests under controlled network and device conditions, useful for detecting regressions.
- Real User Monitoring (RUM): Browser telemetry records actual device, network, route, and timing distributions, revealing problems hidden by fast developer machines.
- Resource timing: Measure transfer size, request count, cache hits, and long tasks. A long task is substantial main-thread work that delays input processing.
- Performance budgets: Set limits such as JavaScript transfer below 200 KB for an initial route or LCP below 2.5 seconds under a chosen test condition.
- Attribution: Connect a slow metric to route, release version, device class, and resource name so engineers can identify the responsible change.
- Privacy: Collect only necessary telemetry, avoid sensitive values, and follow applicable consent and data-protection requirements.
XI. Error Logging — Diagnosing Failures in Production
A. Error Logging
Error logging records failures with enough context to reproduce and repair them without exposing confidential information. Production logs are an operational record, not a substitute for user-facing error handling.
- Structured events: Log JSON fields such as timestamp, severity, service, route, release, request ID, and error type so systems can search and aggregate them.
- Severity levels: Use
infofor normal lifecycle events,warnfor recoverable anomalies, anderrorfor failed operations requiring investigation. - Correlation: A request ID connects frontend reports, backend logs, and database traces for one user action without logging the user’s password or access token.
- Exception tracking: Services such as Sentry can capture stack traces, source-map locations, breadcrumbs, affected releases, and error frequency.
- Safe messages: Return a generic message such as “Something went wrong” to users while retaining technical details in protected logs.
- Alerting: Alert on error rate, latency, and repeated critical failures rather than every isolated exception. Thresholds should distinguish a one-off failure from a release-wide regression.
- Retention and access: Restrict log access, define retention periods, and redact personal data. Logs can themselves become a security and compliance risk.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →