I am using NextJS to product SSR pages, and these pages are language-specific. I would like to set the lang property to declare the language of the text.
So far I have:
import Document, { Html, Head, Main, NextScript } from "next/document"
import Router from "next/router"
class MyDocument extends Document {
render() {
const { lanaguage } = Router.router.query
return (
<Html lang={language}>
<Head />
<body className="antialiased text-white text-base font-sans">
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
However, Router.router
is always null
when using a Custom Document (_document.js
). Is there another way to get the URL params/query when using a Custom Document?
I am using NextJS to product SSR pages, and these pages are language-specific. I would like to set the lang property to declare the language of the text.
So far I have:
import Document, { Html, Head, Main, NextScript } from "next/document"
import Router from "next/router"
class MyDocument extends Document {
render() {
const { lanaguage } = Router.router.query
return (
<Html lang={language}>
<Head />
<body className="antialiased text-white text-base font-sans">
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
However, Router.router
is always null
when using a Custom Document (_document.js
). Is there another way to get the URL params/query when using a Custom Document?
2 Answers
Reset to default 4I have been able to solve this by using:
import Document, { Html, Head, Main, NextScript } from "next/document"
class MyDocument extends Document {
render() {
const { lanaguage } = this.props.__NEXT_DATA__.query
return (
<Html lang={lanaguage}>
<Head />
<body className="antialiased text-white text-base font-sans">
<Main />
<NextScript />
</body>
</Html>
)
}
}
export default MyDocument
I am unsure if it is bad practice to use this.props.__NEXT_DATA__
. However, it does have the information I require.
Since Next.js v10, if you're using the built-in i18n routing, Next will automatically set the lang
attribute of the document.
From the documentation:
Since Next.js knows what language the user is visiting it will automatically add the
lang
attribute to the<html>
tag.Next.js doesn't know about variants of a page so it's up to you to add the
hreflang
meta tags usingnext/head
. You can learn more abouthreflang
in the Google Webmasters documentation.