Go back

Internationalization in Next.js

I've been lost in the process of benchmarking my website's performance for the past few days now. But, while I was doing that, I came across an accessibility issue; One of them was something I was not new to — missing alt tags in image elements — and the other was around Internationalization.

Swiftly, I went on and provided the appropriate fix to the alt attribute error. The i18n — short for Internationalization — issue came up because the lang attribute in the html element was absent. To fix this and comply with the WCAG guidelines, I needed a way to do it.

How to set HTML lang attribute in Next.js

Next.js already provides a next.config.js file, to add other customizable functions. Fixing the i18n issue would require me to populate my config with the snippet below;

i18n: {
  locales: ['en'],
  defaultLocale: 'en',

The locales property in the object is required, and you can also add additional locales to the array, by taking a look at the numerous options we have here. By providing a defaultLocale prop, you're telling the browser: "this is the language I want you to render the content of this site in unless it is specified by the visitor"

Alternatively, you can fix this issue by going into the pages route and create a file, let's call it _document.js, and proceed to add the content of the snippet below into it.

import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
  return (
    <Html lang="en">
      <Head />
        <Main />
        <NextScript />

The snippet above is similar to the common HTML boilerplate that is generated for you when you hit these key combinations — shift key + ! — in VScode. Take a look at something similar below;

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <!-- content -->

You can decide to use any of the approaches to fix this issue whenever you want. Thank you for reading, and I hope you'd find it helpful.