← All blogs

FullStack Engineering CourseLesson 19 of 20 22 min

Web Performance, Accessibility and Front-End Security

Core Web Vitals

Users judge a web app by how quickly it shows something useful, how quickly it reacts and how stable the page is. Google's Core Web Vitals measure exactly these three things, and they also affect search ranking for public pages:

MetricMeasuresGoodCommon causes of poor scores
LCP (Largest Contentful Paint)How long until the largest visible element (a hero image, a heading, a table) is shown2.5 seconds or lessSlow server responses, large images, render-blocking JavaScript and CSS
INP (Interaction to Next Paint)How long the page takes to respond visibly to clicks, taps and key presses, across the whole visit200 milliseconds or lessLong JavaScript tasks on the main thread, heavy re-renders
CLS (Cumulative Layout Shift)How much content jumps around while the page loads0.1 or lessImages without dimensions, ads and banners inserted late, web fonts swapping

INP replaced FID (First Input Delay) as a Core Web Vital in March 2024, because FID measured only the first interaction. The scores that count are measured on real users' devices, at the 75th percentile. Lab tools such as Lighthouse in Chrome DevTools are useful while developing, but a fast developer laptop on office Wi-Fi is not your users' reality. Collect real-user data (real user monitoring, RUM) too:

TypeScript
import { onLCP, onINP, onCLS } from "web-vitals";

function send(metric: { name: string; value: number; rating: string; id: string }) {
  navigator.sendBeacon("/api/telemetry/web-vitals", JSON.stringify(metric));   // survives page unload
}

onLCP(send);
onINP(send);
onCLS(send);

Loading less, sooner

The fastest code is code the browser never downloads. Ways to ship less JavaScript and get the important parts on screen first:

  • Code splitting: split the bundle by route, so users download only the screens they open.
  • Tree shaking: import only what you use (import { debounce } from "lodash-es", not the whole library), so the bundler can drop the rest.
  • Measure the bundle with an analyser (rollup-plugin-visualizer for Vite, webpack-bundle-analyzer), and question every large dependency.
  • Render on the server where it helps (lesson 18), so the first HTML already contains content.
  • Compress text assets with Brotli or gzip, and serve them over HTTP/2 or HTTP/3, which send many files over one connection at once.
  • Give built files content hashes in their names (app.3f9a1c.js) and cache them for a year with Cache-Control: public, max-age=31536000, immutable. A new release has new names, so users never get stale code.
  • Serve static assets from a CDN (Azure Front Door), close to users.
  • Use preconnect for third-party origins you will certainly call, and preload for the one font or image the first screen needs.
TypeScript
import { lazy, Suspense } from "react";

// Each lazy route becomes its own JavaScript file, downloaded only when the route is visited.
const ClaimsPage = lazy(() => import("./features/claims/ClaimsPage"));
const ReportsPage = lazy(() => import("./features/reports/ReportsPage"));   // heavy charting library lives here

export function AppRoutes() {
  return (
    <Suspense fallback={<PageSkeleton />}>
      <Routes>
        <Route path="/claims/*" element={<ClaimsPage />} />
        <Route path="/reports/*" element={<ReportsPage />} />
      </Routes>
    </Suspense>
  );
}

Images

Images are often the largest part of a page and the LCP element:

  • Use modern formats (WebP or AVIF), which are much smaller than JPEG and PNG for the same quality.
  • Serve sizes that match the screen with srcset and sizes, so a phone does not download a desktop-sized image.
  • Always set width and height (or a CSS aspect ratio), so the browser reserves the space and nothing jumps (CLS).
  • Lazy-load images below the first screen with loading="lazy", but never the LCP image; mark that one with fetchpriority="high".
HTML
<img
  src="/img/claims-dashboard-800.webp"
  srcset="/img/claims-dashboard-400.webp 400w, /img/claims-dashboard-800.webp 800w, /img/claims-dashboard-1600.webp 1600w"
  sizes="(max-width: 600px) 100vw, 800px"
  width="800" height="450"
  alt="Claims dashboard showing approval rates by payer"
  fetchpriority="high" />

For video, adaptive bitrate streaming (HLS or DASH) splits the video into short segments at several qualities, and the player switches quality as the network speed changes, so playback continues instead of stalling.

Keeping the page responsive

The browser runs JavaScript, layout and painting on one main thread. Any task longer than 50 ms blocks clicks and typing, which is what makes INP poor. Ways to keep it free:

  • Avoid unnecessary re-renders: React.memo, useMemo and useCallback for expensive components and values (or the React Compiler, which adds memoisation automatically). Measure with the React DevTools Profiler first; memoising cheap components only adds overhead.
  • Virtualise long lists: render only the rows that are visible, not all 10,000.
  • Debounce and throttle frequent events.
  • Keep typing responsive during heavy updates with useDeferredValue or useTransition, which tell React the update can wait.
  • Move heavy computation (parsing a large file, encryption, complex calculations) to a web worker, which runs on a separate thread.

Virtualisation keeps a list of any length fast, because the page only ever contains the few dozen rows on screen:

TypeScript
import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";

export function ClaimList({ claims }: { claims: Claim[] }) {
  const parentRef = useRef<HTMLDivElement>(null);
  const virtualizer = useVirtualizer({
    count: claims.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 48,          // row height in pixels
    overscan: 10,                    // render a few extra rows above and below for smooth scrolling
  });

  return (
    <div ref={parentRef} style={{ height: 600, overflow: "auto" }}>
      <div style={{ height: virtualizer.getTotalSize(), position: "relative" }}>
        {virtualizer.getVirtualItems().map((row) => (
          <div key={claims[row.index].id}
               style={{ position: "absolute", top: 0, transform: `translateY(${row.start}px)`, height: row.size, width: "100%" }}>
            <ClaimRow claim={claims[row.index]} />
          </div>
        ))}
      </div>
    </div>
  );
}

Debouncing and throttling both limit how often a function runs:

  • Debounce: wait until the events stop for a set time, then run once. Use it for search boxes: search 300 ms after the user stops typing, not on every key press.
  • Throttle: run at most once per period while the events continue. Use it for scroll and resize handlers.
TypeScript
import { useEffect, useState } from "react";

export function useDebouncedValue<T>(value: T, delayMs = 300): T {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delayMs);
    return () => clearTimeout(timer);            // a new key press cancels the pending update
  }, [value, delayMs]);
  return debounced;
}

function ClaimSearch() {
  const [text, setText] = useState("");
  const query = useDebouncedValue(text);
  const results = useQuery({ queryKey: ["claim-search", query], queryFn: () => api.search(query), enabled: query.length > 2 });
  return <input value={text} onChange={(e) => setText(e.target.value)} aria-label="Search claims" />;
}

Service workers and PWAs

A service worker is a script that the browser runs in the background, between the page and the network. It can cache files and responses, so the app loads instantly on later visits and can work offline, and it enables push notifications. A progressive web app (PWA) combines a service worker with a web app manifest, so users can install the app and launch it like a native app.

Choose a caching strategy per kind of request: cache-first for versioned static assets, network-first for API data, and stale-while-revalidate (show the cached copy, update it in the background) for content that may be slightly old. Be careful with sensitive data: do not cache patient or financial API responses on shared devices, and clear caches on sign-out. Libraries such as Workbox handle the details.

Monitoring real users and product analytics

  • Real user monitoring (RUM) collects Core Web Vitals, JavaScript errors and slow requests from real browsers, for example with the Application Insights JavaScript SDK or the web-vitals code above.
  • Session replay tools (such as FullStory) record what users did on a page to help reproduce problems. They must mask all personal and sensitive fields, and they need clear user consent.
  • Product analytics (Google Tag Manager, Segment, Mixpanel) track how features are used. Send only the events you need, never sensitive data, and respect cookie consent and privacy laws.
  • Every third-party script slows the page and can read everything on it. Review each one, load it only where needed, and remove those nobody uses.

Accessibility

Accessibility means everyone can use the app, including people using screen readers, keyboards only, magnification or voice control. WCAG 2.2 level AA is the usual target, and it is a legal requirement in many countries and for many public-sector and healthcare customers. The basics catch most problems:

  • Use semantic HTML: button for actions, a for navigation, label for every input, headings in order, and table for tabular data. A clickable div is invisible to keyboards and screen readers.
  • Make everything work with the keyboard alone, with a visible focus indicator.
  • Manage focus: move it into a dialog when it opens and back when it closes, and to the new content after navigation.
  • Give text enough contrast with its background: at least 4.5 to 1 for normal text.
  • Give images meaningful alt text, or alt="" if they are decorative.
  • Use ARIA attributes only when HTML has no suitable element; wrong ARIA is worse than none.
  • Announce dynamic changes (such as "Claim approved") with a live region (role="status").
  • Test with automated checks (axe in tests and Storybook), the keyboard, and a screen reader (NVDA, VoiceOver).

Internationalisation

Internationalisation (i18n) prepares an app to work in many languages and regions; localisation (l10n) adapts it to a specific one. Plan for it early, because retrofitting it means touching every string:

  • Keep all text in translation files, with message IDs (react-i18next or FormatJS), never hard-coded in components.
  • Never build sentences by joining fragments ("You have " + n + " claims"). Word order and plural rules differ between languages. Use messages with placeholders and plural forms (ICU message format).
  • Format numbers, currencies and dates with the Intl APIs and the user's locale; never format them by hand.
  • Support right-to-left languages (Arabic, Hebrew) with CSS logical properties (margin-inline-start instead of margin-left).
  • Store dates in UTC, and convert to the user's time zone only for display.
JavaScript
const amount = 1234567.5;
console.log(new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount));
console.log(new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount));
console.log(new Intl.DateTimeFormat("en-GB", { dateStyle: "medium" }).format(new Date("2026-11-20")));
Output
₹12,34,567.50
$1,234,567.50
20 Nov 2026

Front-end security: XSS

Cross-site scripting (XSS) happens when an attacker gets their JavaScript to run in your page, for example through a claim note containing a script tag. That script can then do anything the user can: read data, call APIs, steal tokens. React protects you by default: text placed in JSX is escaped, so it is shown as text, not run as code. The protection disappears in a few places:

  • dangerouslySetInnerHTML: avoid it. If you must render user-supplied HTML (such as rich-text notes), clean it first with a sanitiser such as DOMPurify.
  • URLs: a link whose href comes from user data can be javascript:..., which runs code when clicked. Allow only http and https URLs.
  • Direct DOM access (innerHTML, eval, new Function) and third-party scripts.
TypeScript
import DOMPurify from "dompurify";

function ClaimNote({ html }: { html: string }) {
  const clean = DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });   // strips scripts and event handlers
  return <div dangerouslySetInnerHTML={{ __html: clean }} />;
}

function safeHref(url: string): string | undefined {
  try {
    const parsed = new URL(url, window.location.origin);
    return parsed.protocol === "https:" || parsed.protocol === "http:" ? parsed.href : undefined;
  } catch {
    return undefined;
  }
}

A Content Security Policy (CSP) is the second line of defence. This response header tells the browser which sources of scripts, styles and connections are allowed, so injected scripts are blocked even if a bug lets them in:

Content-Security-Policy:
  default-src 'self';
  script-src 'self' 'nonce-r4nd0mPerRequest' 'strict-dynamic';
  style-src 'self';
  img-src 'self' data: https://claimsfiles.blob.core.windows.net;
  connect-src 'self' https://claims-api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  object-src 'none'

Start with Content-Security-Policy-Report-Only to see what would be blocked without breaking anything, then switch to enforcing. Avoid 'unsafe-inline' and 'unsafe-eval', which undo most of the protection; use a new random nonce on each response for the scripts you include. Add the other security headers too: Strict-Transport-Security (always use HTTPS), X-Content-Type-Options: nosniff, Referrer-Policy and Permissions-Policy. frame-ancestors 'none' stops other sites from showing your app in a frame to trick users into clicking (clickjacking).

Front-end security: tokens and CSRF

Where a browser app keeps its credentials matters:

  • Tokens in localStorage or sessionStorage can be read by any script on the page, so a single XSS bug leaks them. Avoid this for anything sensitive.
  • Tokens kept in JavaScript memory are safer, but are lost on refresh, and XSS can still use them while the page is open.
  • The recommended pattern is a BFF (lessons 8 and 12): the server keeps the tokens, and the browser only holds a session cookie marked HttpOnly (scripts cannot read it), Secure (sent over HTTPS only) and SameSite.

Cookies bring back an older attack: cross-site request forgery (CSRF). A malicious site makes the user's browser send a request to your app, and the browser attaches your cookie automatically. Defences:

  • SameSite cookies: Lax (the browser default) or Strict stop the cookie being sent on most cross-site requests.
  • Anti-forgery tokens: the server issues a token that the page must send back in a header or form field, which another site cannot read (ASP.NET Core: AddAntiforgery and UseAntiforgery).
  • Require a custom header (such as X-Requested-With) on API calls; browsers do not let another site add custom headers without a CORS preflight, which your server refuses.
  • Never change data with GET requests.

Configure CORS (cross-origin resource sharing) narrowly: list the exact origins that may call your API, and never combine a wildcard origin with credentials. CORS is not a security boundary for your API, since non-browser clients ignore it; it only controls what browsers allow.

Finally, the npm supply chain is part of your security. Commit lock files, install with npm ci in pipelines, scan dependencies (lesson 17), review new packages before adding them, and use Subresource Integrity (an integrity hash on script tags) for any script loaded from a third-party CDN.

Check your understanding

QuestionShort answer
What are the Core Web Vitals?LCP (loading, 2.5 s or less), INP (responsiveness, 200 ms or less) and CLS (visual stability, 0.1 or less).
Lab data or field data?Field data from real users decides the scores; lab tools such as Lighthouse help while developing.
How do you cache built assets safely?Content-hashed file names with a one-year immutable cache; a new release gets new names.
Debounce or throttle?Debounce runs once after events stop (search boxes); throttle runs at most once per period while they continue (scroll).
Why virtualise long lists?Only visible rows are rendered, so the page stays fast however long the list is.
What moves work off the main thread?Web workers.
What are the accessibility basics?Semantic HTML, keyboard support with visible focus, labels, contrast, alt text, careful ARIA, and live regions for updates.
Why not join strings to build sentences?Word order and plural rules differ between languages; use messages with placeholders and plural forms.
When does React not protect against XSS?dangerouslySetInnerHTML, user-supplied URLs (javascript:), direct DOM access and third-party scripts.
What does a CSP do?Tells the browser which sources of scripts and other content are allowed, blocking injected scripts.
Where should a browser app keep tokens?Ideally on the server, behind a BFF, with an HttpOnly, Secure, SameSite session cookie in the browser.
How do you prevent CSRF?SameSite cookies, anti-forgery tokens or required custom headers, and no state changes on GET.

Summary

  • Track LCP, INP and CLS from real users, and fix the biggest problems first.
  • Ship less JavaScript: split by route, tree-shake, analyse bundles, compress, cache hashed assets and use a CDN.
  • Optimise images with modern formats, srcset, dimensions and correct priorities.
  • Keep the main thread free: memoise where measured, virtualise lists, debounce input, and use workers for heavy work.
  • Use service workers and PWAs where offline or installability helps, without caching sensitive data carelessly.
  • Build accessibility and internationalisation in from the start, in the design system.
  • Defend against XSS with React's escaping, sanitising and a strict CSP; keep tokens out of the browser with a BFF; prevent CSRF; and watch the supply chain.

The final lesson covers AI engineering: integrating large language models, embeddings and vector search, retrieval-augmented generation (RAG), agents and tools with Semantic Kernel and the Model Context Protocol, AI-assisted development, and evaluating and guarding AI features.

Found this useful? Share it: LinkedIn X

Comments