Setting the document language

Declaring the page language for accessibility and SEO

Problem

A webpage is displayed in French, but the HTML document itself is not marked as such (e.g., <html lang="en">). This failure to declare the language causes screen readers to attempt to pronounce the French content using English phonetics. It also prevents browsers from offering automatic translation and impacts search engine indexing.

Solution

Read the lang parameter from the URL in the root layout component. Pass this lang parameter to the <html> element's lang attribute. This explicitly declares the language of the entire document to browsers and assistive technologies.

Steps

1. Access the lang param in the root layout

In the Next.js App Router, the layout.tsx file inside a dynamic segment (like [lang]) automatically receives the value of that segment as a params prop.

2. Set the lang attribute on the <html> element

Modify your app/[lang]/layout.tsx file to accept the params prop and apply its lang property to the <html> tag's lang attribute.

// app/[lang]/layout.tsx

export default function RootLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: { lang: string };
}) {
  return (
    <html lang={params.lang}>
      <body>{children}</body>
    </html>
  );
}

This ensures that a request to /fr/about results in the rendered page starting with <html lang="fr">. This simple change correctly informs screen readers, search engines, and browsers what language the content is written in.