Skip to content

Commit e92856f

Browse files
committed
add hreflangs
1 parent 124a42e commit e92856f

File tree

2 files changed

+29
-9
lines changed

2 files changed

+29
-9
lines changed

src/components/PageMetadata.tsx

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
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

7-
import { DEFAULT_LOCALE, SITE_URL } from "@/lib/constants"
5+
import { getFullUrl } from "@/lib/utils/url"
6+
7+
import { SITE_URL } from "@/lib/constants"
88

99
type NameMeta = {
1010
name: string
@@ -33,7 +33,7 @@ const PageMetadata = ({
3333
canonicalUrl,
3434
author,
3535
}: PageMetadataProps) => {
36-
const { locale, asPath } = useRouter()
36+
const { locale, locales, asPath } = useRouter()
3737
const { t } = useTranslation()
3838

3939
const desc = description || t("site-description")
@@ -51,10 +51,7 @@ const PageMetadata = ({
5151
* @example ethereum.org/about/ -> ethereum.org/about
5252
* @example ethereum.org/pt-br/web3/ -> ethereum.org/pt-br/web3
5353
*/
54-
const url = new URL(
55-
join(locale === DEFAULT_LOCALE ? "" : locale!, path),
56-
SITE_URL
57-
).href.replace(/\/$/, "")
54+
const url = getFullUrl(locale, path)
5855
const canonical = canonicalUrl || url
5956

6057
/* Set fallback ogImage based on path */
@@ -105,6 +102,16 @@ const PageMetadata = ({
105102
/>
106103
))}
107104
<link rel="canonical" key={canonical} href={canonical} />
105+
{locales
106+
?.filter((loc) => loc !== locale)
107+
.map((loc) => (
108+
<link
109+
key={loc}
110+
rel="alternate"
111+
hrefLang={loc}
112+
href={getFullUrl(loc, path)}
113+
/>
114+
))}
108115
</Head>
109116
)
110117
}

src/lib/utils/url.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,11 @@
1-
import { DISCORD_PATH, MAIN_CONTENT_ID } from "@/lib/constants"
1+
import { join } from "path"
2+
3+
import {
4+
DEFAULT_LOCALE,
5+
DISCORD_PATH,
6+
MAIN_CONTENT_ID,
7+
SITE_URL,
8+
} from "@/lib/constants"
29

310
export const isDiscordInvite = (href: string): boolean =>
411
href.includes(DISCORD_PATH) && !href.includes("http")
@@ -35,3 +42,9 @@ export const isHrefActive = (
3542
}
3643

3744
export const isHash = (href: string): boolean => href.startsWith("#")
45+
46+
export const getFullUrl = (locale: string | undefined, path: string) =>
47+
new URL(join(locale || DEFAULT_LOCALE, path), SITE_URL).href.replace(
48+
/\/$/,
49+
""
50+
)

0 commit comments

Comments
 (0)