DEV Community

Cover image for Adding a lang attribute to your Next.js site
Cassidy Williams
Cassidy Williams

Posted on

Adding a lang attribute to your Next.js site

Sometimes when you're running a Lighthouse performance check on your sites, you might come across the issue:

<html> element does not have a [lang] attribute
Enter fullscreen mode Exit fullscreen mode

Luckily, this is a pretty easy thing to fix, whether you're using Next.js, or plain ol' HTML!

Why do I need this?

It's for accessibility! Screen readers often use a different sound library for each language they support. They can easily switch between those sound libraries, but only when a webpage specifies which language to use.

Typically in your average Next.js website, the deployed page ships only a <html> wrapped site, with no language attribute attached.

If you were writing a plain HTML website (or using some other library that allows you to update the shipped HTML files), it would be a simple matter of adding a lang="en" to your outputted HTML, like so:

<html lang="en">
Enter fullscreen mode Exit fullscreen mode

With Next.js, it's a little bit more involved, but luckily not too difficult!

Create a Custom Document

Inside of your pages/ directory (or wherever you put your page components), make a file called _document.js. This overrides the default document that is shipped with your Next.js site. Don't worry though, we won't break anything!

Inside of that file, add the following:

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="en"> {/* Add whichever language you want here */}
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}
Enter fullscreen mode Exit fullscreen mode

Boom, you're done! Make sure you don't delete the Html, Head, Main, and NextScript components, because they are required for your site to be properly rendered. Now, next time you run your performance and accessibility audits, your language settings should be in the clear!

Top comments (4)

Collapse
 
thatafro profile image
Méhluli Hikwa

Here is another way you could do it, by adding i18n in next.config.js
This helps if you have multi/tones of pages.

module.exports = {
...

i18n: {
    locales: ["en"],
    defaultLocale: "en",
},

...
Enter fullscreen mode Exit fullscreen mode

}

Collapse
 
dawkaka profile image
Yussif Mohammed

Yeah, it works.
But remember to restart the server otherwise you won't see the effect.

Collapse
 
adrai profile image
Adriano Raiano

Done the same here in Step 11: dev.to/adrai/static-html-export-wi...

Collapse
 
emurrell profile image
Eric Murrell

Great article