diff --git a/packages/gitbook-v2/src/middleware.ts b/packages/gitbook-v2/src/middleware.ts index 79d5929bb..b7904a578 100644 --- a/packages/gitbook-v2/src/middleware.ts +++ b/packages/gitbook-v2/src/middleware.ts @@ -141,10 +141,12 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) { // Make sure the URL is clean of any va token after a successful lookup // The token is stored in a cookie that is set on the redirect response // - const requestURLWithoutToken = normalizeVisitorAuthURL( - mode === 'url' ? requestURL : siteURL - ); - if (requestURLWithoutToken.toString() !== requestURL.toString()) { + const incomingURL = mode === 'url' ? requestURL : siteURL; + const requestURLWithoutToken = normalizeVisitorAuthURL(incomingURL); + if ( + requestURLWithoutToken !== incomingURL && + requestURLWithoutToken.toString() !== incomingURL.toString() + ) { return writeResponseCookies( NextResponse.redirect(requestURLWithoutToken.toString()), cookies diff --git a/packages/gitbook/src/lib/visitor-token.ts b/packages/gitbook/src/lib/visitor-token.ts index 3350da828..64f0c9793 100644 --- a/packages/gitbook/src/lib/visitor-token.ts +++ b/packages/gitbook/src/lib/visitor-token.ts @@ -151,9 +151,13 @@ export function getVisitorAuthCookieValue(basePath: string, token: string): stri * Normalize the URL by removing the visitor authentication token from the query parameters (if present). */ export function normalizeVisitorAuthURL(url: URL): URL { - const withoutVAParam = new URL(url); - withoutVAParam.searchParams.delete(VISITOR_AUTH_PARAM); - return withoutVAParam; + if (url.searchParams.has(VISITOR_AUTH_PARAM)) { + const withoutVAParam = new URL(url); + withoutVAParam.searchParams.delete(VISITOR_AUTH_PARAM); + return withoutVAParam; + } + + return url; } /**