Back to Blog Page
Frontend Development

How to Add the lang Attribute to the Root of your Next JS Website without _document.js

How to Add the lang Attribute to the Root of your Next JS Website without _document.js

Written by Kolade Chris | Dec 21, 2022 | #Next.js #React | 1 minute Read

The lang attribute is not available by default in Next JS. And unfortunately, it’s not a good thing for accessibility not to have the lang attribute in the root element of your Next JS app.

And if you want to write less code as possible like me, then creating a whole file in _document.js to add the lang attribute to the root HTML element of your Next JS app might be an overkill.

If you decide to do it with the _document.js file, this is how it’ll look:

1
import Document, { Head, Html, Main, NextScript } from 'next/document';
2
3
class MyDocument extends Document {
4
static async getInitialProps(context) {
5
const initialProps = await Document.getInitialProps(context);
6
return { ...initialProps };
7
}
8
9
render() {
10
return (
11
<Html lang="en">
12
<Head />
13
<body>
14
<Main />
15
<NextScript />
16
</body>
17
</Html>
18
);
19
}
20
}
21
22
export default MyDocument;

To me, this is too much code. That’s why I’ll show you how to add the lang attribute to the root element of your Next JS app with the built-in next.config.js file.

How to Add the lang Attribute to your Next Website with the next.config.js file

Head over to your next.config.js and add this object:

1
i18n: {
2
locales: ['en'],
3
defaultLocale: 'en',
4
},

Save the file and restart the server so this can reflect. The en value of the locale key represents the value your lang attribute will have.

By the time you inspect your website, you should see something like this:

ss1.png

Thank you for reading. If you find this article helpful, kindly share it with your friends and family.