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
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">
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>
)
}
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!