Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(theme): canonical url should be not change after hydration if url accessed with/without trailing slash #9130

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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