Next.js and accessibility - best practices for developing inclusive web applications

Next.js is a dynamic open-source framework built on top of React. It offers a seamless and efficient way to build modern web applications. It provides a variety of features and improvements to boost developer productivity and optimize application performance. The features include Server Side Rendering (SSR), Static Site Generator (SSG), File System Based Routing, Incremental Static Regeneration (ISR), Image Optimization, Code Splitting, Pre-fetching, Serverless Functions, SEO, and more.

The significance of accessibility in web development

According to the World Wide Web Consortium (W3C), Web accessibility means that websites, tools, and technologies are designed and developed so that people with disabilities can use them.

In web development, accessibility refers to the process of creating websites and web apps that can be explored and utilized by everyone, regardless of their physical or cognitive limitations. It guarantees appropriate perception, navigation, and interaction with web information by people with ailments or impairments.

Some instances of impairment that affect the way individuals use the web include the following:

  • Visual - limited or total inability to perceive or distinguish between colors
  • Auditory - loss of hearing or deafness
  • Physical/motor - challenges in moving different body parts, and doing so precisely
  • Speech - impairment or total inability to speak
  • Cognitive - having trouble recollecting, picking up new information, focusing, or implementing choices

To avoid these problems, some people employ assistive technologies when using the internet. These solutions include Braille terminals, screen readers that read the content on each page aloud, speech recognition software that transcribes spoken words into text, and even alternative keyboards that can be used by people with disabilities.

There are many reasons why accessibility is paramount in web development:

  • Equity in access and inclusivity - web accessibility fosters inclusivity by guaranteeing that people with disabilities can take full advantage of digital activities. Without regard to a person's capabilities, it lowers barriers and offers everyone access to web information, services, and opportunities.
  • Legal and ethical obligations - web accessibility is mandated by laws and regulations in many countries. Apart from avoiding legal problems, following these laws demonstrates ethical responsibility by granting everyone access on an equitable basis.
  • Enhanced user experience - accessibility improvements frequently benefit all users, not just people with disabilities. The usability, readability, and navigability are all improved by considering accessibility. Everyone wins when there is coherent and well-organized content, logical navigation, and suitably labeled elements, which improves user efficiency and satisfaction.

Why Next.js is a suitable framework for building inclusive web applications

Several factors make Next.js a popular framework for creating inclusive web applications.

Accessibility support

Next.js places a strong emphasis on accessibility and offers integrated features that make it simpler to develop accessible web applications. It has properties like support for Accessible Rich Internet Applications (ARIA), automated creation of accessible HTML markup, and integration with renowned accessibility frameworks.

Performance enhancement

Next.js enhances performance with techniques like prefetching, automated code splitting, and preloading. Enhanced user experience and initial page load time make your application accessible across various devices, even with limited network capabilities.

Support for internationalization (i18n)

Out of the box, Next.js offers outstanding assistance for internationalization. It has options including locale-based automatic routing, support for language negotiation, and integration with famous internationalization libraries. It makes it simpler to create multilingual apps that serve a wide range of users.

Huge ecosystem

The Next.js community supports multiple packages, plugins, and extensions, resulting in a flourishing environment. This ecosystem offers extra tools and resources to boost efficiency, improve accessibility, and meet particular inclusive design needs.

Understanding accessibility

An explanation of accessibility in relation to web development

The technique of designing and developing websites and web apps that can be accessed and utilized by individuals with impairments is known as accessibility in web development. It attempts to guarantee that users of all abilities, including those with cognitive, motor, visual, auditory, or neurological impairments, can perceive, comprehend, and engage with digital content satisfactorily.

Web accessibility is crucial to provide an inclusive online environment where all users, regardless of ability, can access the data, services, and features offered by websites and web applications. The promotion of equitable access to information and services for everyone is not only encouraged by law in many countries but also by ethical principles.

Key concepts of web accessibility

Web accessibility encompasses many unique ideas/principles which focus on a distinct component of building an inclusive online experience.

The Web Content Accessibility Guidelines (WCAG) specify four key guidelines for building accessible websites. These four principles contain online accessibility recommendations that you can use as a guide and strive to implement on your site whenever and wherever it is practical.

Perceivable

Users need to be able to perceive the information and interface elements displayed to them. Most online users rely on visual perception, but some rely on sound and touch.

  • Provide text alternatives - provide alternate text (alt text) for non-text information, such as images, audio, and video, so people who cannot see or access the content can nevertheless understand it.
  • Offer substitute methods for consuming time-based media - offer alternatives to time-based media. To assist users with hearing difficulties, provide subtitles for multimedia material (videos) and transcripts for audio information.
  • Create flexible content structures - ensure that information is displayed in multiple formats without compromising its structure or value.
  • Create content that is simple to see and hear - utilizing color contrast is crucial so that even color blind people can read your content and comprehend any visual information you want to communicate. Furthermore, users should be able to change or mute background music playing on your website.

Operable

Users should be able to properly operate and engage with a website or web application regardless of their physical capabilities or the devices they use.

  • Keyboard accessibility - guarantee that all features and interactive components can be used solely with the keyboard and without a mouse. This is crucial for users who have difficulties with mobility or use alternative input devices.
  • Allow enough time for web page interaction - users should have enough time to read, watch, and interact with all forms of material on your website. Users should have the option to extend or cancel any time-limited actions on your website.
  • Navigable - give users simple and predictable navigation patterns to aid them in quickly navigating the information and reaching various website sections.

Understandable

The written and visual information on your website should all be simple to understand for users.

  • Readable - use clear and concise language to ensure that content is comprehensible for all users, including those with cognitive limitations.
  • Clean and consistent interface - create the user interface with a straightforward and recognizable design, according to well-known conventions, and eliminate any unexpected or perplexing components.

Robust

Ensure that web applications and content function correctly across several user agents, such as different browsers, assistive technologies, and emerging technologies.

  • Compatibility - a website or web application must be compatible with user agents (browsers and assistive technologies) to give all users reliable and continuous access.
  • Graceful degradation - ensuring a website works smoothly even if some functionalities aren't supported entirely by all browsers or systems.

Benefits of creating accessible web applications

There are many advantages for organizations and individuals in making web applications accessible.

Enhanced search engine optimization (SEO) and search ranking

Many accessibility best practices follow search engine optimization (SEO) principles. Techniques like utilizing informative alt text for photos, giving well-structured content, and ensuring quick page loads can all affect search rankings, increasing organic traffic and visibility.

Improved usability for all users

Accessibility measures that help people with disabilities frequently enhance usability for all users. Users with diverse abilities, as well as individuals operating multiple devices or encountering problematic surroundings, benefit from the straightforward and consistent design, properly-structured content, and simple navigation.

Cost reductions and future-proofing

In the long term, time and money are saved through implementing accessibility from the start of the development process. The app is kept adaptive to changing technologies and user needs, reducing the need for backward accessibility repairs or redesigns.

Larger user base

Developers can reach a larger audience by making a website or web application accessible. It covers those with disabilities, seniors experiencing impairments brought on by aging and assistive technologies users. Accessible websites may draw in a bigger audience, increasing user interaction and satisfaction as well as the possibility of corporate expansion.

Better mobile experience

Web applications that are accessible offer better mobile usage. Developers frequently optimize for smaller screens, touch interactions, and mobile assistive devices while keeping accessibility in mind. Users that access the application from mobile devices will have a smooth and simple experience consequently.

Next.js accessibility features

By default, Next.js offers a few accessibility features that contribute to making the web more inclusive for all users. We'll explore a few of these capabilities and discuss how to apply them to your Next.js applications.

Broadcasting your route

Screen readers and other assistive devices declare the page title when the page loads while switching between pages presented on the server so that users know the variation. The browser-side transitions supported by Next.js for better efficiency (via next/link) go beyond conventional page navigation. Next.js by default provides a route announcer to guarantee that client-side transitions are also notified to assistive technology.
The document.title, the <h1> tag, and ultimately the URL pathname are all examined by the Next.js route announcer to determine the page name to announce.

Automated <head> tag management

The <head> tag is crucial for both SEO and accessibility because it aids search engines and assistive technology to understand the goal and content of your document.
Next.js offers a built-in component called next/head that enables you to attach elements to the <head> of the page. The component can be used on any of your Next.js pages by importing it from next/head and enclosing your elements inside of it.

import Head from 'next/head';

const MyPage = () => {
  return (
    <div>
      <Head>
        <title>My Page</title>
        <meta name="description" content="Description of the page" />
      </Head>
      {/* Page content */}
    </div>
  );
};

Using next/head also has the advantage of clearing the contents of the <head> tag when unmounting the component. As a result, each page in your application states what it needs in the <head> section without assuming what previous pages have been added. It ensures that the metadata and links on your pages are correct and appropriate.

Linting

Next.js comes with built-in ESLint functionality that includes Next.js-specific rules. To help identify accessibility problems early, such as missing alt text, wrong aria-* attributes, or unsupported role attributes, Next.js includes eslint-plugin-jsx-a11y by default.
By adding a .eslintrc file to the root of your project, you can customize the ESLint configuration. Visit the official documentation for Next.js to learn more about using ESLint.

Dynamic <Link> component accessibility

Accessible features for screen readers are automatically added by the Next.js <Link> component. Pages (identified by the href) are prefetched automatically by the <Link> component in the background. Before a user clicks a link, Next.js will download and cache the page's code and data. By doing this, the page loads much faster and responds to navigational requests more quickly. Users that have slow connections and experience excessive latency will benefit from this.
The Link component has been enhanced in Next.js to enable accessibility features, including keyboard navigation and support for screen readers. The tabIndex attribute, which regulates the order in which elements acquire focus when traversing with the keyboard, is now supported by the Link component. The Link component can receive focus and be triggered with the keyboard because it has a tabIndex value of 0 by default. The focus shifts to the following element with the lowest tabIndex value when a user pushes the "Tab" key on the keyboard.

import Link from 'next/link';

export const Navigation = () => {
  return (
    <nav role="navigation" aria-label="Main Navigation">
      <Link href="/" tabIndex={1}>
        Home
      </Link>
      <Link href="/about" tabIndex={2}>
        About
      </Link>
    </nav>
  );
}

Your applications will be more accessible thanks to the tabIndex property support added to the Link component in Next.js.

[@portabletext/react] Unknown block type "newsletter", specify a component for it in the `components.types` prop

Best practices for developing inclusive Next.js applications

We are going to explore the best practices for creating inclusive Next.js applications, along with examples of how to put them into effect in code.

Create using semantic HTML

Utilizing semantic HTML components that explain the intent and organization of your content is one of the most crucial components of inclusive design. Semantic HTML elements are elements that serve a specific function and play a definite role in the content, such as <header> for the document header, <nav> for navigation, and <section> for the document section, and more.

These elements give users relevant data along with capabilities and are understood by browsers and assistive technologies. In addition to enhancing accessibility, semantic HTML elements offer an intuitive content structure.

<nav>
  <ul>
    <li>
      <Link href="/">Home</Link>
    </li>
    <li>
      <Link href="/contact">Contact Us</Link>
    </li>
  </ul>
</nav>

The <nav> tag is utilized instead of div to improve the accessibility of web pages.

Keyboard accessibility

Adding keyboard accessibility to your web pages is a crucial component of inclusive design. When your web pages are keyboard accessible, visitors can navigate them without the assistance of a mouse or touch screen and interact solely with the keyboard. Keyboard accessibility is crucial for users with mobility or motor disabilities and people who prefer using the keyboard for comfort or effectiveness.

You must ensure that all interactive components on your web pages can be focused and operated by the keyboard to enable keyboard accessibility. Focusable elements are those that support keyboard focus, such as inputs, buttons, links, and custom components that use the tab index attribute. Checkboxes, radio buttons, select, and custom components that use keyboard event handlers are examples of operable elements since they may be triggered or changed by the keyboard.

Using any HTML element or custom component that can be focused and operated by the keyboard is supported by Next.js, which promotes keyboard accessibility.

'use client'
import { useRef } from 'react';

export const MyComponent = () => {
  const buttonRef = useRef(null);

  const handleButtonClick = () => {
    // Button click functionality
  };

  const handleKeyDown = (event) => {
    if (event.key === 'Enter' || event.key === ' ') {
      event.preventDefault(); // Prevent any default button behavior
      buttonRef.current.click(); // Activate button click programmatically
    } else if (event.key === 'ArrowRight') {
      // Navigate to the next element using the keyboard
    } else if (event.key === 'ArrowLeft') {
      // Navigate to the previous element using the keyboard
    }
  };

  return (
    <div>
      <button
        ref={buttonRef}
        onClick={handleButtonClick}
        onKeyDown={handleKeyDown}
        tabIndex={0} // Make sure the button is focusable with the keyboard
      >
        Click Me
      </button>
    </div>
  );
};

When a user presses the Enter or Space key as the button is focused, the handleKeyDown function gets called. Then, the button's default behavior is stopped, and the handleButtonClick method gets activated dynamically to simulate a button click.

It creates a more inclusive and accessible experience by enabling keyboard users to trigger the button with the keyboard alone. Depending on the needs of your application, additional keyboard navigation behaviors can be introduced to handle the ArrowRight and ArrowLeft keys as well as any other pertinent keys.

Leverage ARIA roles and attributes

You can utilize a collection of attributes and roles called ARIA (Accessible Rich Internet Applications) to improve the accessibility of your web elements. Screen readers and other assistive technology can access richer data and context thanks to ARIA attributes and roles. As an illustration, when an element such as an icon button lacks a label or visual text content, you can use an ARIA label to supply one. The function of an element, such as a button, menu, dialog, and the like, can also be specified using the role keyword.

<nav>
  <ul role="menu">
    <li role="menuitem">
      <Link href="/">Home</Link>
    </li>
    <li role="menuitem">
      <Link href="/contact">Contact Us</Link>
    </li>
  </ul>
</nav>

When the element is nav, the navigation role is automatically applied. A menu is represented by an element with the role="menu" attribute. Each element is identified as a menu item within the menu structure by the role="menuitem" attribute. This role indicates that each list item in the navigation menu represents a selectable option. This function helps assistive technology identify the menu structure in the list of navigational elements.

You improve the accessibility of the navigation area by incorporating these ARIA roles and attributes. Users with disabilities can navigate and engage with your Next.js application more effectively by utilizing assistive technologies, as they can now better read and communicate the structure and intent of the navigation menu.

Offer alternative text for multimedia content

Offering text-based alternatives for multimedia content like images, videos, audio, or animations is another best practice for creating accessible Next.js applications. Users with auditory, visual, or cognitive disabilities may be able to access and comprehend the information and features of your multimedia material with the use of text-based alternatives. Users with limited data, sluggish connections, or insufficient bandwidth can visit your website using text-based equivalents instead of downloading huge files. You must use the alt attribute of the image tag to define alternative text for your photos. The alt text must be brief, informative, and contextually appropriate.

<Image
    src="/path/to/image"
    width={500}
    height={500}
    alt="A brief and concise description of the image"
/>

The alt attribute offers a concise and informative text replacement for the image. If a user cannot see the image, the alt text should explain the picture's meaning or substance.

If a video contains conversations or significant sounds, you should provide subtitles or captions in the track element. For people with auditory impairment, the track element could be used to provide captions or subtitles in several languages.

<video controls>
    <source src="/video.mp4" type="video/mp4" />
    <track kind="subtitles" src="/subtitles-en.vtt" label="English" />
    <track kind="captions" src="/captions-en.vtt" label="English (Captions)" />
</video>

You can increase the accessibility and inclusivity of your Next.js application for users with various preferences and abilities by providing text-based substitutes for multimedia information.

Utilizing assistive technologies for testing

Testing your application with accessibility tools can help you find and correct any accessibility problems or flaws that you might have missed in your code. You can conduct accessibility testing using the React Testing Library and Jest tools.

import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

test('should be accessible', () => {
  render(<MyComponent />);
  expect(screen.getByRole('button')).toBeVisible();
});

You can also utilize a few other accessibility tools, such as Lighthouse, Axe, Wave and the like. Users with impairments or those who use assistive technology, such as screen readers, keyboard navigation, or voice control, can also help test your app. You may get ideas and feedback on how to improve your app's usability and accessibility by testing it with users.

Conclusion

In this article, you learned about accessibility in Next.js and how best to implement them. You also learned how Next.js supports accessibility with in-built features that come by default. For more information about accessibility in Next.js, you can visit the documentation.