Reputation: 11
I'm working on a multi-language statically built (next export) Next.js site. I can't use next internationalization so I've had to hack together a solution, mostly based on this nextjs-18n-static-page-starter
My page structure looks like this:
pages
┣ [lang]
┃ ┣ category
┃ ┃ ┣ [slug].js
┃ ┃ ┗ index.js
┃ ┗ index.js
┣ _app.js
┣ _document.js
┗ index.js
I would like to set the html lang attribute in a custom document. Is there any way to dynamically pull this from the url at the document level?
I have this hacky solution going, but it doesn't update when the user changes their language in the app (which does correctly redirect to a new url):
export default class MyDocument extends Document {
render() {
const queryLang = this?.props?.__NEXT_DATA__?.query?.lang;
const lang = ( queryLang === null || queryLang === undefined ) ? DEFAULT_LANG : queryLang;
return (
<Html lang={lang}>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
Upvotes: 0
Views: 1744
Reputation: 7294
Since Next.js v10, if you're using the built-in i18n routing, Next will automatically set the lang
attribute of the document.
if your language is en-US
all you need to do is add the following in you next.config.js
file
module.exports = {
i18n: {
locales: ["en-US"],
defaultLocale: "en-US",
},
...
}
From the documentation:
Search Engine Optimization
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.
Upvotes: 0
Reputation: 11
Setting it in the app did the trick. Here's the code I ended up with (thanks to @juliomalves for pointing me in the right direction)...
const App = function ({ Component, pageProps }) {
i18next.changeLanguage(pageProps.language);
useEffect(() => {
const lang = ( pageProps.language === null ||
pageProps.language === undefined )
? DEFAULT_LANG
: pageProps.language;
document.documentElement.lang = lang;
}, [pageProps.language]);
return <Component {...pageProps} />;
};
Upvotes: 1