How to architect a frontend that works for everyone — screen reader users, keyboard-only navigators, low-vision users, and people with motor or cognitive disabilities. Accessibility is not a feature toggle. It is a design constraint that touches every layer of the stack.
FrontendX EngineeringSystem Design Series
What Are We Building?
Web accessibility (a11y) means designing and building websites that people with disabilities can use. That includes screen reader users who navigate by audio, keyboard-only users who cannot use a mouse, low-vision users who rely on zoom and high contrast, users with motor impairments who use switch devices or voice control, and users with cognitive disabilities who need clear, predictable interfaces.
The Web Content Accessibility Guidelines (WCAG) 2.2 define four core principles — Perceivable, Operable, Understandable, Robust (POUR). Every accessibility requirement maps to one of these four pillars. Meeting AA-level conformance is the legal standard in most jurisdictions (EU, US Section 508, UK Equality Act).
This article is not a checklist. It is a system-design walkthrough of how I build a11y-first frontends. We will cover the accessibility tree, focus management, ARIA patterns, color contrast, motion sensitivity, testing strategies, and performance implications — with real code, not bullet points.
Figure 1 — WCAG 2.2 POUR principles form a pyramid. Each layer builds on the one below it. Robust ARIA markup is useless if the content is not Perceivable.
Let's start with the requirements. What concrete outcomes are we designing toward?
1 · Requirements & Scoping
Before writing a single ARIA attribute, I define what "accessible" means for this project. The answer depends on your users, your jurisdiction, and your product category.
Functional requirements
Full keyboard operability: Every interactive element must be reachable and activatable via keyboard alone. No "click to interact" paths that bypass the keyboard. Tab order must match the visual reading order. Arrow keys, Enter, Escape must work in composite widgets (menus, tabs, grids).
Screen reader compatibility: All information and functionality must be exposed to assistive technology via the accessibility tree. Custom components must have correct roles, states, and properties. Dynamic content changes must be announced via live regions.
Color and contrast compliance: Text must meet WCAG AA contrast ratios (4.5:1 for small text, 3:1 for large). Non-text UI components (borders, icons, state indicators) must meet 3:1. Information must not be conveyed by color alone.
Focus management: Visible focus indicators on all interactive elements. Modals must trap focus and restore it on close. Dynamic content (toasts, errors, new page sections) must programmatically receive focus where appropriate. Skip links must be present on every page.
Reduced motion support: Animations and transitions must respect the prefers-reduced-motion media query. Parallax, auto-scrolling carousels, and decorative animations must be disabled when the user requests it.
Semantic HTML foundation: Use native HTML elements with their built-in accessibility before reaching for ARIA. Landmark regions (<nav>, <main>, <aside>), heading hierarchy (<h1>–<h6>), and form controls (<label>, <fieldset>) must be correctly structured.
Non-functional requirements
Performance: Accessibility features must not cause layout shifts or degrade interaction responsiveness. Live regions and focus management should be O(1) additions to the render cycle, not expensive queries.
Maintainability: A11y concerns should be localized in composable hooks and components, not scattered across every file. A developer adding a new button should not need to think about ARIA — the component system should handle it.
Testability: Accessibility must be verifiable in CI. Automated scans (axe, Lighthouse) should catch regressions. Keyboard-navigation and screen-reader tests should be part of the normal test suite.
Progressive enhancement: The app must remain usable without JavaScript (for critical content paths). ARIA fallbacks must degrade gracefully.
Internationalization: ARIA attributes and accessible names must support localization. The lang attribute must be set on the document and updated for in-page language switches. Screen readers use this to select the correct pronunciation engine.
Tip
I deliberately scope this article to WCAG 2.2 AA. AAA conformance is not achievable for most content-heavy sites (it would require 7:1 contrast for all text, which eliminates many design systems). Target AA as the legal and ethical baseline, then layer AAA enhancements where practical — larger text sections, high-contrast themes, sign-language videos for critical content.
2 · Architecture & High-Level Design
Accessibility is not a single component — it is a set of constraints that permeate the entire frontend architecture. I organize a11y concerns into four layers:
Layer 1: Semantic Foundation
The base layer is correct HTML structure. Landmark elements (<header>, <nav>, <main>, <aside>, <footer>) define page regions. Heading hierarchy establishes document outline. Form controls use native <label> elements. Lists use <ul> / <ol>. This layer costs zero JavaScript, zero bundle, and provides 70% of the a11y value.
semantic-html.htmlhtml
[object Object]
Layer 2: ARIA Enhancement
When native HTML does not provide the necessary semantics — for custom widgets like tabs, accordions, dialogs, and tree views — ARIA attributes fill the gap. The First Rule of ARIA: do not use ARIA if you can use a native HTML element with the semantics you need. A native <button> is always better than a <div role="button">.
aria-accordion.tsxtypescript
[object Object]
Key Insight
The useId() hook is critical for ARIA references. Every aria-controls, aria-labelledby, and aria-describedby must point to a validid that exists in the DOM. Using hardcoded IDs breaks when a component renders twice on the same page. React 18's useId() guarantees unique, stable IDs across server and client.
Layer 3: Interaction Abstraction
Focus management, keyboard event handling, and live-region announcements should be abstracted into reusable hooks and components. A useFocusTrap hook handles modal dialog focus. A useLiveRegion hook manages dynamic announcements. A <SkipLink> component is dropped into the root layout once. These abstractions ensure consistent behavior and make it easy to audit.
Layer 4: Visual & Motion
CSS variables for colors, focus-ring styles, and motion preferences. A design-token layer that ensures contrast ratios are enforced at the theme level (not ad-hoc per component). A global stylesheet that respects prefers-reduced-motion.
I rejected the approach of "retrofitting accessibility" via a single HOC or plugin. That pattern works for simple fixes (adding alt text) but fails for interaction patterns (focus trap, keyboard nav) that require the component to be designed for them from the ground up.
Retrofit HOC (rejected)
Wrap every component with an a11y HOC. Cannot handle focus management or keyboard nav patterns that need component-level coordination.
Single a11y library (rejected)
React Aria or Reach UI for everything. Good but couples entire app to one library. Hard to customize rendering.
Layered architecture (chosen)
Semantic HTML base → ARIA enhancement hooks → focus/interaction abstractions → theme tokens. Each layer is independently testable and replaceable.
3 · Data Model & State Shape
Accessibility introduces two types of state that are not part of the visual UI model: focus state and announcement state. Both must be modeled explicitly, not as side effects of visual state.
The Focusable entity
Every interactive element needs a focus model that is independent of its visual state. I use a discriminated union for focus targets:
type FocusTarget =
| { kind: "element"; ref: HTMLElement }
| { kind: "composite"; activeDescendantId: string; containerRef: RefObject<HTMLElement> }
| { kind: "none" };
interface FocusState {
/** The element or composite that currently has focus */
current: FocusTarget;
/** The element that had focus before a modal opened (for restoration) */
previous: HTMLElement | null;
/** Ordered list of focusable elements in the current context */
focusableElements: HTMLElement[];
/** Index into focusableElements */
focusIndex: number;
}
The Announcement entity
Live regions need a queue of messages to announce. A naive implementation overwrites the previous message before the screen reader can read it. I use a message queue:
interface Announcement {
id: string;
message: string;
priority: "polite" | "assertive";
timestamp: number;
}
interface AnnouncementState {
queue: Announcement[];
/** The currently displayed message in the live region */
current: Announcement | null;
/** Whether the live region is currently being announced */
isAnnouncing: boolean;
}
// Example usage:
// Dispatch a polite announcement when search results load
function SearchResults({ results }: { results: string[] }) {
const { announce } = useAnnouncements();
useEffect(() => {
announce(`${results.length} search results loaded.`, "polite");
}, [results.length, announce]);
return <ul role="listbox">{/* ... */}</ul>;
}
Design tokens as data
Color contrast ratios and motion preferences should be modeled as data, not scattered across CSS files. I store them in a token-level TypeScript object that can be validated in CI:
I audit these tokens in CI with a script that computes ratios from the raw hex values and fails the build if any token drops below 4.5:1. This is cheaper and more reliable than relying on developers to manually check contrast in Figma.
4 · Interface Definition (API)
Accessibility APIs are contracts between components and assistive technology. Unlike a REST API, these contracts are enforced by the browser's accessibility tree, not by TypeScript. But we can still define clearly typed abstractions.
Hook API: useFocusTrap
useFocusTrap.tstypescript
[object Object]
Hook API: useAnnouncements
useAnnouncements.tsxtypescript
[object Object]
Component API: SkipLink
SkipLink.tsxtypescript
[object Object]
Utility API: Contrast checking
contrast.tstypescript
[object Object]
These APIs form the a11y primitive library. Every component in the system uses these building blocks rather than implementing focus traps or live regions from scratch.
5 · Component Deep Dive
Let's examine the three most important a11y subsystems in detail: focus trapping, live-region announcements, and skip links. Each is a standalone pattern you can drop into any React app.
Focus trap — the nuclear option
A focus trap restricts Tab / Shift+Tab cycling to a set of elements inside a container. This is essential for modals, sidebars, and any overlay that should not let focus escape into the background page.
The implementation is deceptively simple. On activation, save the currently focused element, then focus the first focusable child. Intercept the Tab key: if Tab on the last child, jump to the first. If Shift+Tab on the first child, jump to the last. On deactivation, restore focus to the saved element.
FocusTrap.tsxtypescript
[object Object]
The edge cases that bite you
Empty trap: If the trap has zero focusable elements, Tab should not crash. Fall back to focusing the container itself with tabIndex=-1.
Dynamic content: The focusable elements list must be recalculated when children change. Use a MutationObserver or recalculate on each Tab keypress.
Nested traps: A modal inside a modal (e.g., confirm dialog in a settings dialog). The inner trap deactivates the outer trap temporarily.
Portals: If the trap container is rendered in a portal (common for modals), the DOM hierarchy differs from the React hierarchy. The querySelector still works because it traverses the real DOM, but ensure the portal is mounted before attempting focus.
Live regions — announcing without interrupting
Live regions tell screen readers to announce dynamic content changes without moving focus. The two politeness levels are aria-live="polite" (finish current utterance first) and aria-live="assertive" (interrupt immediately). Use polite for 95% of cases.
LiveRegion.tsxtypescript
[object Object]
Warning
The aria-atomic="true" attribute is crucial. Without it, a screen reader only announces the changed portion of the live region's content. With aria-atomic="true", it reads the entire content as a single unit. For a toast that says "Item saved," the entire string should be re-announced — not just "saved."
Skip links — the forgotten hero
A skip link is the first focusable element on the page. It lets keyboard users bypass repetitive navigation and jump directly to the main content. Without it, a user must tab through every nav link, sidebar item, and toolbar before reaching the content.
SkipLink.tsxtypescript
[object Object]
Skip links must be visible on focus but hidden otherwise. The common pattern is to position them off-screen with position: absolute; top: -40px and slide them into view on focus. Do not use display: none or visibility: hidden — that removes them from the accessibility tree entirely.
6 · Under the Hood
Let's trace what happens inside the browser when a screen reader user encounters an accessible component. Understanding the accessibility tree is the single most important concept in web a11y.
The Accessibility Tree: a debug trace
When the browser parses HTML, it builds two trees: the DOM tree (for rendering and scripting) and the accessibility tree (for assistive technology). The accessibility tree is a subset of the DOM, filtered to elements that carry semantic meaning. <div> and <span> with no ARIA role are pruned. Heading, links, buttons, form controls, and elements with explicit ARIA roles are included.
Figure 2 — The Accessibility Tree is derived from the DOM plus ARIA attributes. Screen readers consume this tree, not the DOM directly. Roles, names, values, and states are computed properties.
Step-by-step trace
Consider this simplified component and trace how the browser resolves it:
// Source component
<button aria-label="Close dialog" onClick={close}>
<span aria-hidden="true">✕</span>
</button>
// Step 1 — DOM construction
HTMLButtonElement
└── HTMLSpanElement (text: "✕")
// Step 2 — Accessibility tree computation
// The button maps to role=button automatically (native semantics)
// aria-label="Close dialog" overrides the accessible name
// The <span> has aria-hidden="true" → pruned from a11y tree
AccessibleNode (role: button, name: "Close dialog")
// No children — span is hidden
// Step 3 — Screen reader query
// NVDA/VoiceOver requests the accessibility tree from the browser
// via platform APIs (IAccessible2 / UIA on Windows, NSAccessibility on macOS)
// The screen reader sees:
// "Button, Close dialog"
// It never sees the ✕ character.
Name computation — the five-step algorithm
The browser computes an accessible name using a specific priority order (per the HTML-AAM spec):
aria-labelledby — references another element's text content. Highest priority.
aria-label — direct string override. Use when no visible label exists.
Native semantics — e.g., <label> for a form control, <figcaption> for a figure, <th> for a table header.
Visible text content — the element's own text content (for links and buttons).
title attribute — last resort, poorly supported by screen readers.
Understanding this algorithm is the key to debugging a11y issues. If a screen reader says "unnamed button," the problem is that none of these five sources provided a name.
Key Insight
The Firefox and Chrome DevTools Accessibility panels let you inspect the accessibility tree directly. Open DevTools → Accessibility → check "Enable full-page accessibility tree." You can see exactly which roles, names, and states the browser computes for each element. This is your most powerful debugging tool for a11y issues.
7 · Data Flow & Communication
Accessibility introduces two communication channels beyond the visual rendering pipeline: the focus channel and the announcement channel. Let's trace a complete interaction to see how they work.
Button onClick saves the current focus target (previousFocusRef) and calls setOpen(true). The modal renders.
Focus trap activates
useEffect detects open=true. It queries the modal container for focusable elements, focuses the first one (usually the Close button). The modal has role='dialog' and aria-modal='true'.
User presses Tab to navigate fields
Tab cycles through form fields inside the modal. Shift+Tab reverses. When reaching the last focusable element (Submit), Tab wraps to the first (Close). Background page is inaccessible.
User presses Escape
onKeyDown handler catches Escape. Calls setOpen(false). The trap deactivates. useEffect restores focus to the trigger button. The live region announces 'Settings dialog closed.'
Announcement flow
Announcements follow a queue-based pipeline. When a component calls announce(message), it enqueues the message. The live region updates at most every 300ms (coalesced), displaying the oldest un-announced message. The screen reader polls the live region and speaks the content. This prevents a rapid fire of notifications that the user cannot keep up with.
Figure 3 — Focus management flow. Tab proceeds through skip link, nav, and main content. A modal traps focus within its boundary and restores focus to the trigger element on close.
8 · Performance Optimization
Accessibility features can introduce performance overhead if not implemented carefully. Focus queries, live-region updates, and ARIA attribute mutations all have a cost.
Debounce live-region updates
If a progress bar updates its value 60 times per second, you should not update a live region 60 times per second. Debounce the announcement to at most once per 300ms. Use a microtask coalescing pattern:
function createAnnouncementQueue() {
let pending: string | null = null;
let timer: ReturnType<typeof setTimeout> | null = null;
return {
push(message: string) {
pending = message;
if (timer) return; // Already scheduled
timer = setTimeout(() => {
if (pending) {
updateLiveRegion(pending);
pending = null;
}
timer = null;
}, 300);
},
};
}
// Usage: create once, reuse across components
const queue = createAnnouncementQueue();
// Multiple rapid calls → one announcement every 300ms
queue.push("Uploading...");
queue.push("50% complete...");
queue.push("Upload complete!"); // Only "Upload complete!" is announced
Optimize focus queries
Querying focusable elements with querySelectorAll on every keystroke or Tab press is expensive for large trees. Cache the focusable elements list and invalidate it only when the DOM changes (use React's reconciliation or a MutationObserver). For most modals with fewer than 50 focusable elements, this is negligible, but for complex data grids or tree views, cache aggressively.
Reduced motion — avoid layout thrashing
reducedMotion.tstypescript
[object Object]
Tradeoff table
Strategy
Pros
Cons
Debounced live region
Prevents announcement flood, consistent timing
Last message may be delayed by 300ms
Cached focusable list
O(1) Tab cycling after initial query
Stale if DOM changes without invalidation
CSS reduced-motion (global)
Zero JS cost, covers all animations
Blunt instrument — disables all animations
JS hook for fine-grained control
Selective animation, conditional effects
Extra JS bundle, per-component awareness
9 · Security Considerations
Accessibility and security intersect in ways that are often overlooked. An attacker can exploit a11y patterns to exfiltrate data or bypass access controls.
aria-hidden as a security boundary: Never use aria-hidden="true" to hide sensitive content from screen readers while leaving it visible on screen. This is a security vulnerability, not a privacy feature. A malicious script can still read the DOM. Use server-side redaction instead.
Focus stealing: An attacker can abuse focus management to trap a user on a malicious element. A focus trap that never releases (no Escape handler, no close button) can effectively "lock" the page for keyboard users. Always provide an escape mechanism: Escape key, visible close button, and a timeout that force-releases focus after a reasonable period.
Live-region injection: If user-generated content is rendered inside a live region without sanitization, an attacker can inject fabricated screen-reader announcements. For example, a chat message containing "Your account has been suspended" rendered in a live region could trick a screen reader user. Always sanitize content before placing it in a live region.
Timing side channels via live regions: The timing of live-region updates can leak information. If an admin panel announces "User deleted" at different speeds based on the user's role, a screen reader user could infer authorization boundaries. Use consistent timing for announcements regardless of success/failure.
Alt text data leakage: Alt text on images is read aloud by screen readers. If an image filename contains sensitive information (e.g., CEO-salary-2024.png), ensure alt text does not expose internal data.
Warning
The most common a11y security mistake is using aria-hidden on a parent element to hide its children from screen readers. This does NOT make the children inaccessible to JavaScript or visually hidden. If you need to hide sensitive data, do it server-side or use conditional rendering that removes the elements from the DOM entirely.
10 · Testing Strategy
Accessibility testing is not optional. I use a three-tier strategy: automated scans for regressions, programmatic checks for contract violations, and manual testing for behavioral correctness.
Tier 1: Automated axe scans (CI gate)
Every page in the app is scanned with @axe-core/playwright in CI. The scan checks for 90+ rules: color contrast, ARIA attribute validity, document structure, heading hierarchy, and more. Failures block the PR.
Tier 2: Unit tests with RTL + user-event
a11y.test.tsxtypescript
[object Object]
Tier 3: Manual screen reader testing
Automated scans catch about 30–40% of a11y issues. The rest require manual verification:
NVDA (Windows + Firefox): Navigate the page with just the screen reader. Listen for announcement quality, not just presence. Does the screen reader say "Button, Submit" or "Submit Button"? The order matters.
VoiceOver (macOS + Safari): Use the rotor (Ctrl+Option+U) to verify landmarks, headings, and links are correctly categorized.
Keyboard-only: Unplug the mouse. Navigate every page with Tab, Shift+Tab, Arrow keys, Enter, and Escape. Verify focus indicators are visible at all times.
Zoom (200%): The page should remain functional at 200% zoom with no horizontal scrolling. Text must not be clipped by overflow: hidden containers.
The contrast-tokens script is the most impactful addition. It validates every design-token pair at build time and fails the pipeline before any component uses a non-compliant color. This is much cheaper than catching it during manual QA or — worse — in an accessibility lawsuit.
11 · Accessibility of the A11y System
Meta, I know. But the tools and dashboards we build for accessibility must themselves be accessible.
a11y audit dashboard: If you build an internal tool that lists accessibility violations, ensure it works with screen readers. Color-coded severity badges must include text labels (not just green/yellow/red dots).
Contrast-checker tool: If you provide a contrast-ratio calculator, ensure the input fields have labels, the results are announced via live region, and the pass/fail indicators include text alternatives.
Focus-order visualizer: If you build a devtools extension that shows tab order, ensure it is keyboard navigable.
Tip
I once shipped an a11y audit dashboard with color-coded severity indicators that had no text labels. A screen reader user on my team pointed out the irony. We fixed it in the same sprint. The first rule of a11y: eat your own dogfood.
Figure 4 — WCAG contrast ratio decision tree. Text vs non-text, small vs large determine the required ratio. AAA is a stricter superset of AA.
12 · Live Demo
You can test the accessibility patterns described in this article right in your browser. Here is what to try:
Keyboard navigation test
Press Tab to focus the skip link, thenEnter to jump to main content. Use Tab to cycle through interactive elements. The focus ring should be clearly visible at all times.
Try Ctrl+Option+U (macOS VoiceOver) or Insert+F7 (NVDA) to open the element list and verify that landmarks, headings, and links are correctly categorized.
Screen reader test
Enable your screen reader (VoiceOver, NVDA, or JAWS). Navigate to the heading "1 · Requirements & Scoping." The screen reader should announce "Level 2 heading, Requirements and Scoping." The live-region element at the top announces page state changes.
Reduced motion test
Enable "Reduce motion" in your OS settings (System Settings → Accessibility → Display → Reduce motion on macOS; Windows Settings → Ease of Access → Display → Show animations in Windows). Refresh this page. The BranchTimeline animation should be disabled.
The full source code for this page follows every pattern described in the article: semantic HTML, ARIA landmarks, skip link, focus management, color contrast (4.5:1+), and reduced-motion support.
13 · Key Takeaways
Accessibility is a constraint, not a feature. It must be designed into the architecture from the start, not retrofitted. Semantic HTML is free and provides 70% of the value. Start there before reaching for ARIA.
The accessibility tree is the ground truth. Screen readers do not read the DOM. They read the accessibility tree that the browser derives from the DOM + ARIA. Debug in the browser's Accessibility panel, not by inspecting HTML.
Focus management is the hardest part. Focus traps, skip links, aria-activedescendant, focus restoration — each pattern has subtle edge cases (empty traps, nested traps, portal rendering). Abstract them into reusable hooks.
Automate what you can; manually test what you cannot. Axe scans catch regressions. Contrast-token validation prevents design drift. But only manual screen reader testing reveals announcement quality issues.
Color is not the only channel. Never convey information through color alone. Add icons, text labels, patterns, or underlines. The WCAG "Use of Color" Success Criterion (1.4.1) requires that color is not the sole means of conveying information.
Respect user preferences.prefers-reduced-motion, prefers-color-scheme, prefers-contrast. These are not styling suggestions — they are user requirements. Honor them at the system level.
WCAG AA is the baseline, not the ceiling. Legal compliance stops at AA. Good engineering goes further: clear announcement messages, logical heading hierarchies, and understandable error messages benefit every user, not just those with disabilities.
Web accessibility is not a checklist you complete before launch. It is a design practice you apply to every component, every interaction, and every line of CSS. The patterns in this article give you a system for building a11y-first frontends at scale. The rest is discipline — and empathy.