@@ -40,14 +40,35 @@ export const SEO = ({
40
40
const currentUrl = slug ? `${ docs } /${ slug } ` : docs ;
41
41
const currentImage = createMetaImagePath ( image , siteUrl , siteImage ) ;
42
42
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` } ,
46
46
} ;
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
47
68
if ( slug && ( slug . startsWith ( 'es/' ) || slug === 'es' ) ) {
48
- hrefLangRelAttributeHash . es = 'canonical' ;
69
+ hrefLangAttributes . es . rel = 'canonical' ;
49
70
} else {
50
- hrefLangRelAttributeHash . en = 'canonical' ;
71
+ hrefLangAttributes . en . rel = 'canonical' ;
51
72
}
52
73
53
74
return (
@@ -82,21 +103,21 @@ export const SEO = ({
82
103
{ pageTranslations && pageTranslations . en !== undefined && (
83
104
< link
84
105
hrefLang = "en"
85
- href = { `${ siteUrl } /docs ${ pageTranslations . en . path } ` }
86
- rel = { `${ hrefLangRelAttributeHash . en } ` }
106
+ href = { `${ hrefLangAttributes . en . href } ` }
107
+ rel = { `${ hrefLangAttributes . en . rel } ` }
87
108
/>
88
109
) }
89
110
{ pageTranslations && pageTranslations . es !== undefined && (
90
111
< link
91
112
hrefLang = "es"
92
- href = { `${ siteUrl } /docs ${ pageTranslations . es . path } ` }
93
- rel = { `${ hrefLangRelAttributeHash . es } ` }
113
+ href = { `${ hrefLangAttributes . es . href } ` }
114
+ rel = { `${ hrefLangAttributes . es . rel } ` }
94
115
/>
95
116
) }
96
117
{ pageTranslations && (
97
118
< link
98
119
hrefLang = "x-default"
99
- href = { `${ siteUrl } /docs ${ pageTranslations . en . path } ` }
120
+ href = { `${ hrefLangAttributes . en . href } ` }
100
121
rel = "alternate"
101
122
/>
102
123
) }
0 commit comments