diff --git a/packages/docusaurus-theme-classic/src/theme/SiteMetadata/index.tsx b/packages/docusaurus-theme-classic/src/theme/SiteMetadata/index.tsx index 9a30c775fff2c..4a275e819c17b 100644 --- a/packages/docusaurus-theme-classic/src/theme/SiteMetadata/index.tsx +++ b/packages/docusaurus-theme-classic/src/theme/SiteMetadata/index.tsx @@ -16,6 +16,7 @@ import { keyboardFocusedClassName, } from '@docusaurus/theme-common/internal'; import {useLocation} from '@docusaurus/router'; +import {applyTrailingSlash} from '@docusaurus/utils-common'; import SearchMetadata from '@theme/SearchMetadata'; // TODO move to SiteMetadataDefaults or theme-common ? @@ -58,10 +59,19 @@ function AlternateLangHeaders(): JSX.Element { // Default canonical url inferred from current page location pathname function useDefaultCanonicalUrl() { const { - siteConfig: {url: siteUrl}, + siteConfig: {url: siteUrl, baseUrl, trailingSlash}, } = useDocusaurusContext(); + + // TODO using useLocation().pathname is not a super idea + // See https://github.com/facebook/docusaurus/issues/9170 const {pathname} = useLocation(); - return siteUrl + useBaseUrl(pathname); + + const canonicalPathname = applyTrailingSlash(useBaseUrl(pathname), { + trailingSlash, + baseUrl, + }); + + return siteUrl + canonicalPathname; } // TODO move to SiteMetadataDefaults or theme-common ? diff --git a/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts b/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts index ae0e55dcddffa..073aa8956f3b0 100644 --- a/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts +++ b/packages/docusaurus-theme-common/src/utils/useAlternatePageUtils.ts @@ -7,6 +7,7 @@ import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; import {useLocation} from '@docusaurus/router'; +import {applyTrailingSlash} from '@docusaurus/utils-common'; /** * Permits to obtain the url of the current page in another locale, useful to @@ -35,17 +36,25 @@ export function useAlternatePageUtils(): { }) => string; } { const { - siteConfig: {baseUrl, url}, + siteConfig: {baseUrl, url, trailingSlash}, i18n: {defaultLocale, currentLocale}, } = useDocusaurusContext(); + + // TODO using useLocation().pathname is not a super idea + // See https://github.com/facebook/docusaurus/issues/9170 const {pathname} = useLocation(); + const canonicalPathname = applyTrailingSlash(pathname, { + trailingSlash, + baseUrl, + }); + const baseUrlUnlocalized = currentLocale === defaultLocale ? baseUrl : baseUrl.replace(`/${currentLocale}/`, '/'); - const pathnameSuffix = pathname.replace(baseUrl, ''); + const pathnameSuffix = canonicalPathname.replace(baseUrl, ''); function getLocalizedBaseUrl(locale: string) { return locale === defaultLocale