Skip to content

Commit 6ae1d75

Browse files
authored
Merge pull request #12259 from ethereum/hreflang
SEO: add hreflangs
2 parents e67d2e5 + 8c6ff4c commit 6ae1d75

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

src/components/PageMetadata.tsx

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
import { join } from "path"
2-
31
import Head from "next/head"
42
import { useRouter } from "next/router"
53
import { useTranslation } from "next-i18next"
64

5+
import { filterRealLocales } from "@/lib/utils/translations"
6+
import { getFullUrl } from "@/lib/utils/url"
77
import { getOgImage } from "@/lib/utils/metadata"
8-
9-
import { DEFAULT_LOCALE, SITE_URL } from "@/lib/constants"
8+
import { SITE_URL } from "@/lib/constants"
109

1110
type NameMeta = {
1211
name: string
@@ -35,9 +34,11 @@ const PageMetadata = ({
3534
canonicalUrl,
3635
author,
3736
}: PageMetadataProps) => {
38-
const { locale, asPath } = useRouter()
37+
const { locale, locales: rawLocales, asPath } = useRouter()
3938
const { t } = useTranslation()
4039

40+
const locales = filterRealLocales(rawLocales)
41+
4142
const desc = description || t("site-description")
4243
const siteTitle = t("site-title")
4344
const fullTitle = `${title} | ${siteTitle}`
@@ -47,7 +48,7 @@ const PageMetadata = ({
4748
const slug = path.split("/")
4849

4950
// Set canonical URL w/ language path to avoid duplicate content
50-
const url = new URL(join(locale!, path), SITE_URL).href
51+
const url = getFullUrl(locale, path)
5152
const canonical = canonicalUrl || url
5253

5354
/* Set fallback ogImage based on path */
@@ -83,6 +84,14 @@ const PageMetadata = ({
8384
/>
8485
))}
8586
<link rel="canonical" key={canonical} href={canonical} />
87+
{locales.map((loc) => (
88+
<link
89+
key={loc}
90+
rel="alternate"
91+
hrefLang={loc}
92+
href={getFullUrl(loc, path)}
93+
/>
94+
))}
8695
</Head>
8796
)
8897
}

src/lib/utils/url.ts

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
1-
import path from "path"
1+
import { join } from "path"
22

3-
import { DISCORD_PATH, MAIN_CONTENT_ID } from "@/lib/constants"
3+
import {
4+
DEFAULT_LOCALE,
5+
DISCORD_PATH,
6+
MAIN_CONTENT_ID,
7+
SITE_URL,
8+
} from "@/lib/constants"
49

510
export const isDiscordInvite = (href: string): boolean =>
611
href.includes(DISCORD_PATH) && !href.includes("http")
@@ -31,7 +36,10 @@ export const isHrefActive = (
3136

3237
export const isHash = (href: string): boolean => href.startsWith("#")
3338

39+
export const getFullUrl = (locale: string | undefined, path: string) =>
40+
addSlashes(new URL(join(locale || DEFAULT_LOCALE, path), SITE_URL).href)
41+
3442
export const addSlashes = (href: string): string => {
3543
if (isExternal(href)) return href
36-
return path.join("/", href, "/")
44+
return join("/", href, "/")
3745
}

0 commit comments

Comments
 (0)