Creating link tags to locales for SEO in NextJS
Jethro Larson

Jethro Larson @jethrolarson

Joined:
Jan 3, 2020

Creating link tags to locales for SEO in NextJS

Publish Date: Jun 30 '22
10 3

This wasn't hard but I didn't find good search results for it so here's a quick tip.

I'm using next-translate with nextjs for localization but this technique will probably work with other localization frameworks like next-i18next.

in pages/_app.ts

import Head from 'next/head';
import type { AppProps } from 'next/app';
import {useRouter} from 'next/router';

const supportedLocales = ['ar-ye', 'en-us', 'fr'];

export default function MyApp({ Component, pageProps }: AppProps): ReactElement {
  const {asPath} = useRouter();
  return (
    <>
      <Head>
        {supportedLocales.map(loc =>
          <link rel="alternate" hrefLang={loc} href={`/${loc}${asPath}`}/>)}
      </Head>
      <Component {...pageProps} />
    </>
  );

}
Enter fullscreen mode Exit fullscreen mode

I hope this helps google find your translated pages!

Comments 3 total

  • tom-voicer
    tom-voicerApr 25, 2024

    Since useRouter is a hook, I assume these link tags are only rendered in the client side, and not server side.

    So basically, this gives zero value for SEO.

    You should really add these tags to the head on server side.

    Correct me if I'm wrong here...

  • alaa sufi
    alaa sufiMar 25, 2025

    thank you
    I edit the code:

    • add key to loop
    • use PUBLIC_SITE_URL
    • add condition to '/' path
     {['ar', 'en', 'nl'].map(loc =>
                <link 
                    key={`/${loc}${asPath}`}
                    rel="alternate" hrefLang={loc}
                    href={`${process.env.NEXT_PUBLIC_SITE_URL}/${loc}${asPath === '/' ? '' : asPath}`} 
                />)}
    
    Enter fullscreen mode Exit fullscreen mode

    then check the result using the website
    hreflang Tags Testing Tool

Add comment