Reputation: 1086
I would like to add <link rel="alternate" hreflang="lang_code"... >
elements to my pages headers to tell all the language and region variants of a page.
Example for the homepage
header:
<link rel="alternate" hrefLang="en" href="https://WEBSITE_URL/" />
<link rel="alternate" hrefLang="de" href="https://WEBSITE_URL/de" />
<link rel="alternate" hrefLang="nl" href="https://WEBSITE_URL/nl" />
Example for the about-us
header:
<link rel="alternate" hrefLang="en" href="https://WEBSITE_URL/about-us" />
<link rel="alternate" hrefLang="de" href="https://WEBSITE_URL/de/über-uns" />
<link rel="alternate" hrefLang="nl" href="https://WEBSITE_URL/nl/over-ons" />
And repeat this in every page with its corresponding path in that language. Is it possible to create it dynamically with Next.js?
Upvotes: 2
Views: 2248
Reputation: 50308
You can generate the <link>
s dynamically based on your locales inside the custom _app
. This way the logic applies to all pages of the app, and updates on client-side navigations.
// pages/_app.js
import { useRouter } from 'next/router'
import Head from 'next/head'
const App = ({ Component, pageProps }) => {
const router = useRouter()
return (
<>
<Head>
{router.locales.map((locale) => {
return (
<link
key={locale}
rel="alternate"
hrefLang={locale}
href={`https://WEBSITE_URL/${locale}${router.asPath}`}
/>
)
})}
</Head>
<Component {...pageProps} />
</>
)
}
export default App
Upvotes: 9