Next.js: How to set HTML lang attribute

Last updated on May 30, 2022 Pennywise Loading... Post a comment

When building a web application, you can set the lang attribute of the <html> tag to explicitly declare the language used on your pages:

<html lang="ja">

Note: The language code used here is ISO 639-1 and you can see the full list of codes on Wikipedia.

In Next.js, the lang attribute isn’t set by default. However, you can easily add it to the <html> tag by overriding the default document. Just follow a few steps below.

1. In the pages folder of your project, create a new file called _document.js (or _document.ts if you’re using TypeScript) .The name must be absolutely correct.

2. Add the following code to _document.js:

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

export default function Document() {
  return (
    <Html lang='en'>
      <Head />
        <Main />
        <NextScript />

Replace en with the language code you want. You should keep all other things unchanged. The <Html>, <Head/>, <Main/> and <NextScript /> components are required for the page to be properly rendered.

File structure:

3. Now boot your app up and use Chrome DevTools to check the result:

That’s it. Further reading:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Notify of
Inline Feedbacks
View all comments

You May Also Like