diff --git a/.changeset/cyan-tigers-bow.md b/.changeset/cyan-tigers-bow.md new file mode 100644 index 000000000..8b8a5419c --- /dev/null +++ b/.changeset/cyan-tigers-bow.md @@ -0,0 +1,5 @@ +--- +"@rspress/theme-default": minor +--- + +feat: preserve query string when redirecting on first visit diff --git a/packages/theme-default/src/logic/useRedirect4FirstVisit.ts b/packages/theme-default/src/logic/useRedirect4FirstVisit.ts index cb90ef74a..2b7b45492 100644 --- a/packages/theme-default/src/logic/useRedirect4FirstVisit.ts +++ b/packages/theme-default/src/logic/useRedirect4FirstVisit.ts @@ -18,7 +18,7 @@ export function useRedirect4FirstVisit() { return; } // Normalize current url, to ensure that the home url is always with a trailing slash - const { pathname } = window.location; + const { pathname, search } = window.location; const cleanPathname = removeBase(pathname); // Check if the user is visiting the site for the first time const FIRST_VISIT_KEY = 'rspress-visited'; @@ -33,19 +33,22 @@ export function useRedirect4FirstVisit() { if (!langs.includes(targetLang)) { return; } - if (targetLang !== currentLang) { - if (targetLang === defaultLang) { - // Redirect to the default language - window.location.replace(pathname.replace(`/${currentLang}`, '')); - } else if (currentLang === defaultLang) { - // Redirect to the current language - window.location.replace(withBase(`/${targetLang}${cleanPathname}`)); - } else { - // Redirect to the current language - window.location.replace( - pathname.replace(`/${currentLang}`, `/${targetLang}`), - ); - } + if (targetLang === currentLang) { + return; + } + let newPath: string; + if (targetLang === defaultLang) { + // Redirect to the default language + newPath = pathname.replace(`/${currentLang}`, ''); + } else if (currentLang === defaultLang) { + // Redirect to the current language + newPath = withBase(`/${targetLang}${cleanPathname}`); + } else { + // Redirect to the current language + newPath = pathname.replace(`/${currentLang}`, `/${targetLang}`); + } + if (newPath) { + window.location.replace(newPath + search); } }, []); }