Skip to content

Commit

Permalink
fix(theme): canonical url should be not change after hydration if url…
Browse files Browse the repository at this point in the history
… accessed with/without trailing slash (#9130)

Co-authored-by: Joshua Chen <sidachen2003@gmail.com>
Co-authored-by: sebastienlorber <lorber.sebastien@gmail.com>
  • Loading branch information
3 people committed Jul 21, 2023
1 parent cd61c7b commit 4ea0a70
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
14 changes: 12 additions & 2 deletions packages/docusaurus-theme-classic/src/theme/SiteMetadata/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?
Expand Down Expand Up @@ -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 ?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 4ea0a70

Please sign in to comment.