Skip to content

Commit

Permalink
Merge pull request #12259 from ethereum/hreflang
Browse files Browse the repository at this point in the history
SEO: add hreflangs
  • Loading branch information
nhsz authored Feb 22, 2024
2 parents e67d2e5 + 8c6ff4c commit 6ae1d75
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
21 changes: 15 additions & 6 deletions src/components/PageMetadata.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { join } from "path"

import Head from "next/head"
import { useRouter } from "next/router"
import { useTranslation } from "next-i18next"

import { filterRealLocales } from "@/lib/utils/translations"
import { getFullUrl } from "@/lib/utils/url"
import { getOgImage } from "@/lib/utils/metadata"

import { DEFAULT_LOCALE, SITE_URL } from "@/lib/constants"
import { SITE_URL } from "@/lib/constants"

type NameMeta = {
name: string
Expand Down Expand Up @@ -35,9 +34,11 @@ const PageMetadata = ({
canonicalUrl,
author,
}: PageMetadataProps) => {
const { locale, asPath } = useRouter()
const { locale, locales: rawLocales, asPath } = useRouter()
const { t } = useTranslation()

const locales = filterRealLocales(rawLocales)

const desc = description || t("site-description")
const siteTitle = t("site-title")
const fullTitle = `${title} | ${siteTitle}`
Expand All @@ -47,7 +48,7 @@ const PageMetadata = ({
const slug = path.split("/")

// Set canonical URL w/ language path to avoid duplicate content
const url = new URL(join(locale!, path), SITE_URL).href
const url = getFullUrl(locale, path)
const canonical = canonicalUrl || url

/* Set fallback ogImage based on path */
Expand Down Expand Up @@ -83,6 +84,14 @@ const PageMetadata = ({
/>
))}
<link rel="canonical" key={canonical} href={canonical} />
{locales.map((loc) => (
<link
key={loc}
rel="alternate"
hrefLang={loc}
href={getFullUrl(loc, path)}
/>
))}
</Head>
)
}
Expand Down
14 changes: 11 additions & 3 deletions src/lib/utils/url.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import path from "path"
import { join } from "path"

import { DISCORD_PATH, MAIN_CONTENT_ID } from "@/lib/constants"
import {
DEFAULT_LOCALE,
DISCORD_PATH,
MAIN_CONTENT_ID,
SITE_URL,
} from "@/lib/constants"

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

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

export const getFullUrl = (locale: string | undefined, path: string) =>
addSlashes(new URL(join(locale || DEFAULT_LOCALE, path), SITE_URL).href)

export const addSlashes = (href: string): string => {
if (isExternal(href)) return href
return path.join("/", href, "/")
return join("/", href, "/")
}

0 comments on commit 6ae1d75

Please sign in to comment.