DEV Community

Jethro Larson
Jethro Larson

Posted on

6 3

Creating link tags to locales for SEO in NextJS

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!

Top comments (2)

Collapse
 
tomvoicer profile image
tom-voicer

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...

Collapse
 
kostia1st profile image
Kostiantyn Kolesnichenko

You are wrong, useRouter gets executed server-side, and provides correct asPath

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs