Skip to content

Commit a223cf8

Browse files
committed
hreflang fix metatag
1 parent a838a02 commit a223cf8

File tree

1 file changed

+31
-10
lines changed

1 file changed

+31
-10
lines changed

src/components/shared/seo/seo.view.js

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,35 @@ export const SEO = ({
4040
const currentUrl = slug ? `${docs}/${slug}` : docs;
4141
const currentImage = createMetaImagePath(image, siteUrl, siteImage);
4242

43-
const hrefLangRelAttributeHash = {
44-
en: 'alternate',
45-
es: 'alternate',
43+
const hrefLangAttributes = {
44+
en: { rel: 'alternate', href: `${siteUrl}/docs` },
45+
es: { rel: 'alternate', href: `${siteUrl}/docs` },
4646
};
47+
48+
if (pageTranslations) {
49+
let esPathname = pageTranslations.es.path;
50+
let enPathname = pageTranslations.en.path;
51+
52+
if (esPathname.endsWith('/')) {
53+
// gatsby-plugin-react-helmet-canonical-urls.noTrailingSlash
54+
esPathname = esPathname.substring(0, esPathname.length - 1);
55+
}
56+
if (enPathname.endsWith('/')) {
57+
// gatsby-plugin-react-helmet-canonical-urls.noTrailingSlash
58+
enPathname = enPathname.substring(0, enPathname.length - 1);
59+
}
60+
hrefLangAttributes.es.href += esPathname;
61+
hrefLangAttributes.en.href += enPathname;
62+
63+
// if no pageTranslations, we must enable `gatsby-plugin-react-helmet-canonical-urls`
64+
}
65+
66+
// we have to setup the `canonical` URL with `hreflang`.
67+
// we must do it here because `gatsby-plugin-react-helmet-canonical-urls` does not cover this case
4768
if (slug && (slug.startsWith('es/') || slug === 'es')) {
48-
hrefLangRelAttributeHash.es = 'canonical';
69+
hrefLangAttributes.es.rel = 'canonical';
4970
} else {
50-
hrefLangRelAttributeHash.en = 'canonical';
71+
hrefLangAttributes.en.rel = 'canonical';
5172
}
5273

5374
return (
@@ -82,21 +103,21 @@ export const SEO = ({
82103
{pageTranslations && pageTranslations.en !== undefined && (
83104
<link
84105
hrefLang="en"
85-
href={`${siteUrl}/docs${pageTranslations.en.path}`}
86-
rel={`${hrefLangRelAttributeHash.en}`}
106+
href={`${hrefLangAttributes.en.href}`}
107+
rel={`${hrefLangAttributes.en.rel}`}
87108
/>
88109
)}
89110
{pageTranslations && pageTranslations.es !== undefined && (
90111
<link
91112
hrefLang="es"
92-
href={`${siteUrl}/docs${pageTranslations.es.path}`}
93-
rel={`${hrefLangRelAttributeHash.es}`}
113+
href={`${hrefLangAttributes.es.href}`}
114+
rel={`${hrefLangAttributes.es.rel}`}
94115
/>
95116
)}
96117
{pageTranslations && (
97118
<link
98119
hrefLang="x-default"
99-
href={`${siteUrl}/docs${pageTranslations.en.path}`}
120+
href={`${hrefLangAttributes.en.href}`}
100121
rel="alternate"
101122
/>
102123
)}

0 commit comments

Comments
 (0)